Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(chat): remove quotes, annotations, and side chats

vastsadb001777fead
diff --git a/apps/desktop/src/components/ChatSurface.tsx b/apps/desktop/src/components/ChatSurface.tsx
index 698fa429c..c479d65ba 100644
--- a/apps/desktop/src/components/ChatSurface.tsx
+++ b/apps/desktop/src/components/ChatSurface.tsx
@@ -6,7 +6,6 @@ import { HomeProjectSwitcher } from "./HomeProjectSwitcher";
import { IconX } from "./icons";
import { TooltipButton } from "./ui";
import { OnboardingChecklist } from "./OnboardingChecklist";
-import { ResponseAnnotationDialog } from "./ResponseAnnotationDialog";
import { SessionPane } from "./SessionPane";
import { useAppStore } from "../stores/app-store";
import { headPermission } from "../lib/pending-permissions";
@@ -230,8 +229,6 @@ export const ChatSurface = memo(function ChatSurface() {
</div>
</div>
) : null}
-
- <ResponseAnnotationDialog />
</div>
);
});
diff --git a/apps/desktop/src/components/ChatTranscript.tsx b/apps/desktop/src/components/ChatTranscript.tsx
index 63aec4989..c08351345 100644
--- a/apps/desktop/src/components/ChatTranscript.tsx
+++ b/apps/desktop/src/components/ChatTranscript.tsx
@@ -1,3 +1,2 @@
export { ChatTranscript } from "../features/chat/transcript/ChatTranscript";
export { SubagentDetail } from "../features/chat/transcript/SubagentDetail";
-export { TranscriptReadOnlyContext } from "../features/chat/transcript/context";
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index 4eb5b4fc4..d98a63ca5 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -99,9 +99,6 @@ export function Composer({
const nativeReadOnly =
nativeSession && activeSessionSummary.capabilities?.canPrompt !== true;
const nativeInputBlocked = nativeReadOnly || (nativeSession && isRunning);
- const hasAnnotations = useAppStore((s) =>
- Boolean(s.activeSessionId && s.responseAnnotations[s.activeSessionId]?.length),
- );
const workspacePath = useAppStore((s) => s.workspace?.path ?? "");
const providers = useAppStore((s) => s.providers);
const providerModels = useAppStore((s) => s.providerModels);
@@ -397,7 +394,7 @@ export function Composer({
const enterToSend = settings?.enterToSend ?? true;
// Chips occupy sentinel characters, which `trim()` preserves — text and
// attachments share one content check.
- const hasDraftContent = Boolean(value.trim()) || hasAnnotations;
+ const hasDraftContent = Boolean(value.trim());
useEffect(() => {
if (!controlsBlocked) return;
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsx
index 4bb54f8f4..63bd8c287 100644
--- a/apps/desktop/src/components/Markdown.tsx
+++ b/apps/desktop/src/components/Markdown.tsx
@@ -53,7 +53,6 @@ import {
safeDecodeUri,
toWorkspaceRel,
} from "../lib/chat-links";
-import { annotationMarkerToken, splitAnnotationMarkerTokens } from "../lib/response-annotations";
import {
isClosedFencedCodeBlock,
MAX_MERMAID_SOURCE_LENGTH,
@@ -485,41 +484,6 @@ function InlineCode({
);
}
-/**
- * Inline numbered marker for one response annotation (ADR response-annotations / D-LOCAL-response-annotations).
- *
- * It mirrors the reference overlay's marker: the number of the annotation in
- * array order, with the annotated excerpt as its tooltip.
- */
-function AnnotationMarker({ index }: { index: number }) {
- const { t } = useTranslation();
- const annotation = useAppStore((state) =>
- state.activeSessionId
- ? (state.responseAnnotations[state.activeSessionId] ?? [])[index - 1]
- : undefined,
- );
- const excerpt = annotation?.text ?? "";
- const comment = annotation?.annotation?.trim() ?? "";
- const tooltip = [
- `${t("chat.annotationSelectedText")} ${excerpt}`,
- comment ? `${t("chat.annotationComment")} ${comment}` : "",
- ]
- .filter(Boolean)
- .join("\n\n");
- return (
- <button
- type="button"
- className="response-annotation-marker"
- data-annotation-index={index}
- aria-label={t("chat.annotationMarker", { index })}
- title={tooltip || undefined}
- onClick={() => undefined}
- >
- {index}
- </button>
- );
-}
-
function Anchor({
node: _node,
children,
@@ -534,7 +498,6 @@ function Anchor({
const showToast = useAppStore((s) => s.showToast);
const linkOpenTarget = useAppStore((s) => s.settings?.linkOpenTarget ?? "workpanel");
- const annotationIndex = annotationMarkerIndexFromHref(href);
const [menuPosition, setMenuPosition] = useState<{ top: number; left: number } | null>(null);
const menuRef = useRef<HTMLDivElement | null>(null);
const anchorRef = useRef<HTMLAnchorElement | null>(null);
@@ -613,13 +576,6 @@ function Anchor({
}
};
- // An annotated pass carries its number here instead of a link: the marker is
- // an inline reference, not a destination (ADR response-annotations / D-LOCAL-response-annotations). Every hook above
- // still runs, so the marker branch cannot change hook order.
- if (annotationIndex !== null) {
- return <AnnotationMarker index={annotationIndex} />;
- }
-
// Plain click previews in the work panel (or external browser based on setting).
// Modified clicks fall through to _blank, which main routes to shell.openExternal.
const onClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
@@ -824,84 +780,11 @@ const markdownComponents: Components = {
table: Table,
};
-/** Href scheme the annotation markers travel on through the markdown pipeline. */
-const ANNOTATION_MARKER_SCHEME = "annotation:";
-
-/** Url resolved for one annotation number. */
-export function annotationMarkerHref(index: number): string {
- return `${ANNOTATION_MARKER_SCHEME}${index}`;
-}
-/** The annotation number one rendered marker element carries, or null. */
-export function annotationMarkerIndexFromHref(href: string | undefined): number | null {
- if (!href || !href.startsWith(ANNOTATION_MARKER_SCHEME)) return null;
- const index = Number(href.slice(ANNOTATION_MARKER_SCHEME.length));
- return Number.isSafeInteger(index) && index > 0 ? index : null;
-}
-
-type MdastLike = {
- type?: string;
- value?: string;
- url?: string;
- children?: MdastLike[];
-};
-
-/**
- * Turn `:codex-annotation{index="N"}` tokens into numbered marker elements
- * (ADR response-annotations / D-LOCAL-response-annotations). The token is the reference implementation's own syntax,
- * so an answer that echoes one renders as a marker instead of raw text.
- */
-export function annotationMarkerMdastTree(tree: MdastLike | null | undefined): void {
- walk(tree);
-
- function walk(node: MdastLike | null | undefined) {
- if (!node?.children) return;
- const next: MdastLike[] = [];
- for (const child of node.children) {
- if (child.type === "text" && typeof child.value === "string") {
- const segments = splitAnnotationMarkerTokens(child.value);
- if (segments.length === 1 && segments[0].kind === "text") {
- next.push(child);
- continue;
- }
- for (const segment of segments) {
- if (segment.kind === "text") {
- if (segment.value) next.push({ type: "text", value: segment.value });
- continue;
- }
- next.push({
- type: "link",
- url: annotationMarkerHref(segment.index),
- children: [
- { type: "text", value: annotationMarkerToken(segment.index) },
- ],
- });
- }
- continue;
- }
- walk(child);
- next.push(child);
- }
- node.children = next;
- }
-}
-
-function remarkAnnotationMarkers() {
- return (tree: MdastLike) => {
- annotationMarkerMdastTree(tree);
- };
-}
-
-const staticRemarkPlugins = [remarkGfm, remarkMath, remarkAnnotationMarkers];
+const staticRemarkPlugins = [remarkGfm, remarkMath];
// Extend the default schema only for the media elements rendered above.
const sanitizeSchema = {
...defaultSchema,
- protocols: {
- ...defaultSchema.protocols,
- // The annotation markers travel on their own scheme; without it the
- // sanitizer drops the href and the raw directive renders as link text.
- href: [...(defaultSchema.protocols?.href ?? []), ANNOTATION_MARKER_SCHEME.replace(/:$/, "")],
- },
attributes: {
...defaultSchema.attributes,
img: [...(defaultSchema.attributes?.img || []), "src", "alt", "title", "className"],
diff --git a/apps/desktop/src/components/ResponseAnnotationDialog.tsx b/apps/desktop/src/components/ResponseAnnotationDialog.tsx
deleted file mode 100644
index d02f2b0e2..000000000
--- a/apps/desktop/src/components/ResponseAnnotationDialog.tsx
+++ /dev/null
@@ -1,205 +0,0 @@
-/**
- * Compact comment editor for one response annotation (ADR response-annotations / D-LOCAL-response-annotations).
- *
- * Add to chat in the selection overlay and the assistant turn's annotate action
- * open it with the excerpt snapshotted when the selection was taken; the
- * composer's annotation list opens it to edit an existing comment. Saving writes
- * only the annotation's `annotation` field: nothing is sent, no session is
- * created, and the excerpt is never re-read from the DOM, so a focus change that
- * collapses the selection cannot lose it.
- */
-import { useEffect, useRef, useState, type FormEvent } from "react";
-import { createPortal } from "react-dom";
-import { useTranslation } from "react-i18next";
-import { useAppStore } from "../stores/app-store";
-import type { ResponseAnnotationEditor } from "../lib/response-annotations";
-import { Button, TooltipButton } from "./ui";
-import { IconChat, IconClose } from "./icons";
-
-export function ResponseAnnotationDialog() {
- const editor = useAppStore((s) => s.responseAnnotationEditor);
- const activeSessionId = useAppStore((s) => s.activeSessionId);
- const saveResponseAnnotationEditor = useAppStore(
- (s) => s.saveResponseAnnotationEditor,
- );
- const closeResponseAnnotationEditor = useAppStore(
- (s) => s.closeResponseAnnotationEditor,
- );
- const owned = editor && editor.sessionId === activeSessionId ? editor : null;
-
- // The editor belongs to the session it was opened in: switching sessions
- // must not carry a half-written comment into another conversation, and the
- // save path must never touch another session's annotations.
- useEffect(() => {
- if (editor && editor.sessionId !== activeSessionId) {
- closeResponseAnnotationEditor();
- }
- }, [editor, activeSessionId, closeResponseAnnotationEditor]);
-
- if (!owned) return null;
- return (
- <CommentEditor
- // A different excerpt or annotation is a different editor: remounting
- // seeds the textarea from that annotation's own comment.
- key={`${owned.sessionId}\u0000${owned.annotationId ?? owned.text}`}
- editor={owned}
- onSave={saveResponseAnnotationEditor}
- onClose={closeResponseAnnotationEditor}
- />
- );
-}
-
-function CommentEditor({
- editor,
- onSave,
- onClose,
-}: {
- editor: ResponseAnnotationEditor;
- onSave: (comment: string) => void;
- onClose: () => void;
-}) {
- const { t } = useTranslation();
- const [comment, setComment] = useState(editor.comment);
- const textareaRef = useRef<HTMLTextAreaElement | null>(null);
- const dialogRef = useRef<HTMLDivElement | null>(null);
-
- useEffect(() => {
- const previouslyFocused = document.activeElement as HTMLElement | null;
- const previousOverflow = document.body.style.overflow;
- document.body.style.overflow = "hidden";
- const frame = requestAnimationFrame(() => {
- const input = textareaRef.current;
- if (!input) return;
- input.focus();
- input.setSelectionRange(input.value.length, input.value.length);
- });
-
- const onKeyDown = (event: KeyboardEvent) => {
- if (event.isComposing || event.keyCode === 229) return;
- if (event.key === "Escape") {
- event.preventDefault();
- // The modal owns Escape, not the application's abort shortcut.
- event.stopImmediatePropagation();
- onClose();
- return;
- }
- if (event.key !== "Tab") return;
- const focusable = dialogRef.current?.querySelectorAll<HTMLElement>(
- "textarea:not([disabled]), button:not([disabled])",
- );
- if (!focusable?.length) return;
- const first = focusable[0];
- const last = focusable[focusable.length - 1];
- if (event.shiftKey && document.activeElement === first) {
- event.preventDefault();
- last.focus();
- } else if (!event.shiftKey && document.activeElement === last) {
- event.preventDefault();
- first.focus();
- }
- };
-
- window.addEventListener("keydown", onKeyDown, true);
- return () => {
- cancelAnimationFrame(frame);
- window.removeEventListener("keydown", onKeyDown, true);
- document.body.style.overflow = previousOverflow;
- if (previouslyFocused?.isConnected && previouslyFocused !== document.body) {
- previouslyFocused.focus();
- if (document.activeElement === previouslyFocused) return;
- }
- // The floating selection pill disappears on open and never takes focus.
- document.querySelector<HTMLElement>(
- '[data-composer-dock] [contenteditable="true"]',
- )?.focus();
- };
- }, [onClose]);
-
- const submit = (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- onSave(comment);
- };
-
- const dialog = (
- <div
- className="overlay session-rename-dialog-overlay"
- role="presentation"
- onPointerDown={(event) => {
- if (event.target === event.currentTarget) {
- event.preventDefault();
- onClose();
- }
- }}
- >
- <div
- ref={dialogRef}
- className="dialog session-rename-dialog response-annotation-dialog"
- role="dialog"
- aria-modal="true"
- aria-labelledby="response-annotation-dialog-title"
- data-testid="annotation-comment-dialog"
- onClick={(event) => event.stopPropagation()}
- >
- <div className="session-rename-dialog-head">
- <div>
- <h2
- id="response-annotation-dialog-title"
- className="session-rename-dialog-title"
- >
- <IconChat size={16} aria-hidden />
- {t("chat.annotationCommentTitle")}
- </h2>
- </div>
- <TooltipButton
- type="button"
- className="session-rename-dialog-close"
- tooltip={t("common.cancel")}
- ariaLabel={t("common.cancel")}
- onClick={onClose}
- >
- <IconClose size={16} />
- </TooltipButton>
- </div>
- <form onSubmit={submit}>
- <div className="response-annotation-quote">
- <span className="response-annotation-quote-label">
- {t("chat.annotationSelectedText")}
- </span>
- <blockquote className="response-annotation-quote-text">
- {editor.text}
- </blockquote>
- </div>
- <textarea
- ref={textareaRef}
- className="field-textarea response-annotation-comment-input"
- value={comment}
- rows={3}
- aria-label={t("chat.annotationCommentTitle")}
- placeholder={t("chat.annotationCommentPlaceholder")}
- onChange={(event) => setComment(event.target.value)}
- onKeyDown={(event) => {
- if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;
- if (event.key !== "Enter" || event.shiftKey) return;
- event.preventDefault();
- event.stopPropagation();
- if (!event.repeat) onSave(event.currentTarget.value);
- }}
- data-testid="annotation-comment-input"
- />
- <div className="session-rename-dialog-actions">
- <Button type="button" variant="ghost" onClick={onClose}>
- {t("common.cancel")}
- </Button>
- <Button type="submit" variant="primary">
- {t("common.save")}
- </Button>
- </div>
- </form>
- </div>
- </div>
- );
-
- return typeof document === "undefined"
- ? dialog
- : createPortal(dialog, document.body);
-}
diff --git a/apps/desktop/src/components/ResponseAnnotationOverlay.tsx b/apps/desktop/src/components/ResponseAnnotationOverlay.tsx
deleted file mode 100644
index 974371a58..000000000
--- a/apps/desktop/src/components/ResponseAnnotationOverlay.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
-import { createPortal } from "react-dom";
-import { useTranslation } from "react-i18next";
-import type { ResponseAnnotation } from "../lib/response-annotations";
-import { annotationRange, annotationRow, placeAnnotationBadges } from "../lib/response-annotation-anchor";
-import { COMPOSER_DOCK_SELECTOR, intersectSelectionQuoteRect, selectionQuoteBounds, type SelectionQuoteRect } from "../lib/selection-quote";
-import { useAppStore } from "../stores/app-store";
-import { IconChevronDown, IconChevronRight, IconPencil, IconX } from "./icons";
-import { TooltipButton } from "./ui";
-
-const EMPTY: ResponseAnnotation[] = [];
-
-/** One session's floating index and out-of-flow source badges; never edits Markdown. */
-export function ResponseAnnotationOverlay({ sessionId, scrollRef, onNavigate }: {
- sessionId: string;
- scrollRef: RefObject<HTMLDivElement | null>;
- onNavigate: (annotation: ResponseAnnotation) => void;
-}) {
- const { t } = useTranslation();
- const annotations = useAppStore((state) => state.responseAnnotations[sessionId] ?? EMPTY);
- const edit = useAppStore((state) => state.openResponseAnnotationEditor);
- const remove = useAppStore((state) => state.removeResponseAnnotation);
- const clear = useAppStore((state) => state.clearResponseAnnotations);
- const [expanded, setExpanded] = useState(true);
- const [activeId, setActiveId] = useState<string | null>(null);
- const toggleRef = useRef<HTMLButtonElement>(null);
- const [geometry, setGeometry] = useState<{
- badges: { id: string; index: number; left: number; top: number; exact: boolean }[];
- highlights: SelectionQuoteRect[];
- }>({ badges: [], highlights: [] });
-
- useEffect(() => {
- if (!annotations.some((annotation) => annotation.id === activeId)) setActiveId(null);
- }, [annotations, activeId]);
-
- useLayoutEffect(() => {
- const root = scrollRef.current;
- if (!root || !annotations.length) {
- setGeometry({ badges: [], highlights: [] });
- return;
- }
- let frame = 0;
- const measure = () => {
- frame = 0;
- const dock = document.querySelector(COMPOSER_DOCK_SELECTOR);
- const bounds = selectionQuoteBounds({ element: root,
- viewport: { width: window.innerWidth, height: window.innerHeight },
- bottomBoundaryTop: dock?.getBoundingClientRect().top,
- });
- if (!bounds) { setGeometry({ badges: [], highlights: [] }); return; }
- const badges: typeof geometry.badges = [];
- const highlights: SelectionQuoteRect[] = [];
- annotations.forEach((annotation, index) => {
- const row = annotationRow(root, annotation.messageId);
- if (!row) return;
- const range = annotationRange(row, annotation.anchor);
- const rects = range ? Array.from(range.getClientRects()) : [row.getBoundingClientRect()];
- const visible = rects.map((rect) => intersectSelectionQuoteRect(rect, bounds))
- .filter((rect): rect is SelectionQuoteRect => rect !== null);
- if (!visible.length) return;
- const rowRect = row.getBoundingClientRect();
- badges.push({ id: annotation.id, index: index + 1,
- left: Math.max(bounds.left, Math.min(rowRect.right + 4, bounds.right - 24)),
- top: visible[0].top, exact: range !== null,
- });
- if (range) highlights.push(...visible);
- });
- setGeometry({ badges: placeAnnotationBadges(badges, bounds.top, bounds.bottom), highlights });
- };
- const schedule = () => { if (!frame) frame = requestAnimationFrame(measure); };
- measure();
- root.addEventListener("scroll", schedule, { capture: true, passive: true });
- window.addEventListener("resize", schedule);
- const resize = new ResizeObserver(schedule);
- resize.observe(root);
- if (root.firstElementChild) resize.observe(root.firstElementChild);
- const dock = document.querySelector(COMPOSER_DOCK_SELECTOR);
- if (dock) resize.observe(dock);
- const mutation = new MutationObserver(schedule);
- mutation.observe(root, { childList: true, subtree: true, characterData: true });
- return () => {
- cancelAnimationFrame(frame);
- root.removeEventListener("scroll", schedule, true);
- window.removeEventListener("resize", schedule);
- resize.disconnect();
- mutation.disconnect();
- };
- }, [annotations, scrollRef]);
-
- if (!annotations.length) return null;
- const choose = (annotation: ResponseAnnotation) => {
- setActiveId(annotation.id);
- setExpanded(true);
- onNavigate(annotation);
- };
-
- return <>
- <aside className="response-annotation-float" data-annotation-layer
- aria-label={t("chat.annotationReview")} data-testid="annotation-float">
- <div className="response-annotation-float-head">
- <button type="button" ref={toggleRef} className="response-annotation-float-toggle"
- aria-expanded={expanded} aria-controls={`annotation-list-${sessionId}`}
- onClick={() => setExpanded((value) => !value)}>
- {expanded ? <IconChevronDown size={14} /> : <IconChevronRight size={14} />}
- {t("chat.annotationChip", { count: annotations.length })}
- </button>
- {expanded ? <TooltipButton type="button" className="composer-annotation-clear"
- tooltip={t("chat.clearAnnotations")} ariaLabel={t("chat.clearAnnotations")} onClick={clear}>
- <IconX size={12} />
- </TooltipButton> : null}
- </div>
- {expanded ? <ol id={`annotation-list-${sessionId}`} className="response-annotation-float-list"
- data-testid="composer-annotation-menu">
- {annotations.map((annotation, index) => <li key={annotation.id}
- className={`composer-annotation-item${activeId === annotation.id ? " active" : ""}`}
- data-testid="composer-annotation-item">
- <div className="composer-annotation-item-head">
- <button type="button" className="response-annotation-locate"
- aria-label={`${t("chat.annotationLocate")} ${index + 1}`}
- onClick={() => choose(annotation)}>
- <span className="response-annotation-number">{index + 1}</span>
- <span className="composer-annotation-item-text" title={annotation.text}>{annotation.text}</span>
- </button>
- <TooltipButton type="button" className="composer-annotation-item-action"
- tooltip={t("chat.annotationEdit")} ariaLabel={`${t("chat.annotationEdit")} ${index + 1}`}
- onClick={() => edit({ messageId: annotation.messageId, text: annotation.text, annotationId: annotation.id })}>
- <IconPencil size={13} />
- </TooltipButton>
- <TooltipButton type="button" className="composer-annotation-item-action"
- tooltip={t("chat.annotationRemove")} ariaLabel={`${t("chat.annotationRemove")} ${index + 1}`}
- onClick={() => { remove(annotation.id); toggleRef.current?.focus(); }}>
- <IconX size={13} />
- </TooltipButton>
- </div>
- {annotation.annotation ? <p className="composer-annotation-item-comment">{annotation.annotation}</p> : null}
- </li>)}
- </ol> : null}
- </aside>
- {createPortal(<div className="response-annotation-source-layer" data-annotation-layer>
- {geometry.highlights.map((rect, index) => <span key={index} aria-hidden="true"
- className="response-annotation-highlight" style={{ top: rect.top, left: rect.left, width: rect.width, height: rect.height }} />)}
- {geometry.badges.map((badge) => {
- // A removal changes the list before its layout measurement runs.
- const index = annotations.findIndex((annotation) => annotation.id === badge.id);
- if (index < 0) return null;
- const annotation = annotations[index];
- return <button key={badge.id} type="button"
- className={`response-annotation-source-badge${activeId === badge.id ? " active" : ""}`}
- style={{ top: badge.top, left: badge.left }}
- aria-label={`${t("chat.annotationLocate")} ${index + 1}`}
- title={badge.exact ? annotation.text : t("chat.annotationRowLocation")}
- onClick={() => choose(annotation)}>{index + 1}</button>;
- })}
- </div>, document.body)}
- </>;
-}
diff --git a/apps/desktop/src/components/SelectionQuoteButton.tsx b/apps/desktop/src/components/SelectionQuoteButton.tsx
deleted file mode 100644
index a044727af..000000000
--- a/apps/desktop/src/components/SelectionQuoteButton.tsx
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * Floating selection overlay (ADR message-quotes-and-side-chats / D-LOCAL-selection-overlay).
- *
- * Mirrors the ChatGPT desktop app's selected-text overlay: a pill that floats
- * above the selection, centered on it, clamped into the bounds of the scroll
- * container it belongs to (never over the docked composer), and that follows the
- * selection while the thread scrolls.
- *
- * It is portaled to `document.body` and positioned in viewport coordinates, so
- * it never participates in the transcript's layout or scroll extent. The
- * selection is serialized back to Markdown when the pill appears — the DOM the
- * range points at can change while it is on screen — and every action only
- * writes a draft, a clipboard entry, a side chat, or the annotation comment
- * editor: nothing is sent to the conversation being read, no session is created,
- * and nothing is written to its transcript.
- */
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
-import { createPortal } from "react-dom";
-import { useTranslation } from "react-i18next";
-import type { RefObject } from "react";
-import { IconCheck, IconCopy } from "./icons";
-import { useCopy } from "./Markdown";
-import { useAppStore } from "../stores/app-store";
-import { selectionAnnotationAnchorWithinRow } from "../lib/response-annotation-anchor";
-import {
- activeSelectionRange,
- COMPOSER_DOCK_SELECTOR,
- placeSelectionQuote,
- quotableRowFor,
- selectionQuoteTarget,
- type SelectionQuoteTarget,
-} from "../lib/selection-quote";
-
-export function SelectionQuoteButton({
- scrollRef,
- title,
-}: {
- /** The transcript this overlay quotes from; selections elsewhere are ignored. */
- scrollRef: RefObject<HTMLElement | null>;
- /** Source title for the quote attribution line. */
- title: string;
-}) {
- const { t } = useTranslation();
- const quoteMessageIntoComposer = useAppStore((s) => s.quoteMessageIntoComposer);
- const openResponseAnnotationEditor = useAppStore(
- (s) => s.openResponseAnnotationEditor,
- );
- const openSideChat = useAppStore((s) => s.openSideChat);
- const { copied, copy } = useCopy();
- const [target, setTarget] = useState<SelectionQuoteTarget | null>(null);
- const [placement, setPlacement] = useState<{
- top: number;
- left: number;
- maxWidth: number;
- } | null>(null);
- const pillRef = useRef<HTMLDivElement | null>(null);
- // A press on the pill must not be read as "the user clicked away", and the
- // host refuses a fork while the visible turn is still running.
- const pressedRef = useRef(false);
- const sessionRunning = useAppStore((s) =>
- s.activeSessionId ? s.runningSessions[s.activeSessionId] === true : false,
- );
-
- useEffect(() => {
- let frame = 0;
- const sync = () => {
- frame = 0;
- if (pressedRef.current) return;
- const dock = document.querySelector(COMPOSER_DOCK_SELECTOR);
- setTarget(
- selectionQuoteTarget({
- scrollRoot: scrollRef.current,
- // The composer floats over the transcript, so the scroller's own
- // bottom edge is under it.
- bottomBoundaryTop: dock ? dock.getBoundingClientRect().top : null,
- }),
- );
- };
- const schedule = () => {
- if (frame) return;
- // A drag fires selectionchange many times per frame, and each pass clones
- // DOM; one rAF per frame keeps a long drag from serializing repeatedly.
- frame = requestAnimationFrame(sync);
- };
- const clear = () => {
- if (frame) {
- cancelAnimationFrame(frame);
- frame = 0;
- }
- setTarget(null);
- setPlacement(null);
- };
- const onPointerDown = (event: PointerEvent) => {
- const node = event.target;
- if (node instanceof Node && pillRef.current?.contains(node)) return;
- // Pressing elsewhere is a new selection or a dismissal: hold the old pill
- // back until the gesture settles.
- pressedRef.current = true;
- clear();
- };
- const onPointerUp = () => {
- if (!pressedRef.current) return;
- pressedRef.current = false;
- schedule();
- };
- // Scroll does not bubble, so the capture phase is what catches the
- // transcript's own scroller. Scrolling something unrelated to the selection
- // (the sidebar, a settings page) must not move the pill.
- const onScroll = (event: Event) => {
- if (pressedRef.current) return;
- const range = activeSelectionRange();
- const row = range ? quotableRowFor(range.startContainer) : null;
- const node = event.target;
- if (!row || !(node instanceof Node) || !node.contains(row)) return;
- schedule();
- };
- document.addEventListener("selectionchange", schedule);
- window.addEventListener("dblclick", schedule);
- window.addEventListener("keyup", schedule);
- window.addEventListener("pointerdown", onPointerDown);
- window.addEventListener("pointerup", onPointerUp);
- window.addEventListener("pointercancel", onPointerUp);
- window.addEventListener("resize", schedule);
- window.addEventListener("scroll", onScroll, { capture: true, passive: true });
- // A selection that already exists on mount (a re-rendered pane) still owns
- // its pill without waiting for the next document event.
- schedule();
- return () => {
- clear();
- document.removeEventListener("selectionchange", schedule);
- window.removeEventListener("dblclick", schedule);
- window.removeEventListener("keyup", schedule);
- window.removeEventListener("pointerdown", onPointerDown);
- window.removeEventListener("pointerup", onPointerUp);
- window.removeEventListener("pointercancel", onPointerUp);
- window.removeEventListener("resize", schedule);
- window.removeEventListener("scroll", onScroll, { capture: true });
- };
- }, [scrollRef]);
-
- // The pill is laid out before it is measured, so the first painted frame
- // already has its final place: no visible jump from a provisional spot.
- useLayoutEffect(() => {
- if (!target) {
- setPlacement(null);
- return;
- }
- const size = pillRef.current?.getBoundingClientRect();
- if (!size) return;
- setPlacement(
- placeSelectionQuote({ anchor: target.anchor, size, bounds: target.bounds }),
- );
- }, [target]);
-
- const dismiss = useCallback(() => {
- // Mirrors the reference behavior: the action consumes the selection, so the
- // pill does not survive its own click.
- window.getSelection()?.removeAllRanges();
- setTarget(null);
- setPlacement(null);
- }, []);
-
- if (!target) return null;
-
- const addToChat = () => {
- if (target.annotatable) {
- // A response turn opens the comment editor on the excerpt snapshotted by
- // the pill; the annotation is attached when that editor saves (D-LOCAL-response-annotations).
- openResponseAnnotationEditor({
- messageId: target.rowAnchorId,
- text: target.markdown,
- anchor: selectionAnnotationAnchorWithinRow(target.rowAnchorId),
- });
- } else {
- quoteMessageIntoComposer({ title, text: target.markdown });
- }
- dismiss();
- };
-
- const askInSideChat = async () => {
- await openSideChat(target.rowAnchorId, target.markdown);
- dismiss();
- };
-
- return createPortal(
- <div
- ref={pillRef}
- className="selection-quote"
- data-testid="selection-quote"
- style={
- placement
- ? {
- top: placement.top,
- left: placement.left,
- maxWidth: placement.maxWidth,
- }
- : { top: 0, left: 0, visibility: "hidden" }
- }
- // Keeping the selection alive through the press is what lets the quote be
- // taken from it rather than from a collapsed caret.
- onPointerDown={(event) => event.preventDefault()}
- >
- <button type="button" className="selection-quote-action" onClick={addToChat}>
- {t("chat.addToChat")}
- </button>
- <span className="selection-quote-sep" aria-hidden="true" />
- <button
- type="button"
- className="selection-quote-action"
- disabled={sessionRunning}
- onClick={() => void askInSideChat()}
- >
- {t("chat.askInSideChat")}
- </button>
- <span className="selection-quote-sep" aria-hidden="true" />
- <button
- type="button"
- className="selection-quote-action icon"
- aria-label={t("chat.copy")}
- title={t("chat.copy")}
- onClick={() => copy(target.markdown)}
- >
- {copied ? <IconCheck size={13} /> : <IconCopy size={13} />}
- </button>
- </div>,
- document.body,
- );
-}
diff --git a/apps/desktop/src/components/icons.tsx b/apps/desktop/src/components/icons.tsx
index db09b34ff..b548bd59c 100644
--- a/apps/desktop/src/components/icons.tsx
+++ b/apps/desktop/src/components/icons.tsx
@@ -84,7 +84,6 @@ import {
Sun,
Target,
Terminal,
- TextQuote,
Trash2,
TriangleAlert,
UserRound,
@@ -152,8 +151,6 @@ export const IconArrowUpDown = icon(ArrowUpDown);
export const IconSearch = icon(Search);
export const IconRefresh = icon(RefreshCcw);
export const IconChat = icon(MessageSquare);
-/** Message reference: quote part of a message into the composer (D-LOCAL-message-quotes). */
-export const IconQuote = icon(TextQuote);
/** Session creation affordance. Keep it distinct from generic add actions. */
export const IconNewSession = icon(MessageSquarePlus);
export const IconFolder = icon(Folder);
diff --git a/apps/desktop/src/components/workpanel/SideChatTab.tsx b/apps/desktop/src/components/workpanel/SideChatTab.tsx
deleted file mode 100644
index 8c6aed4b5..000000000
--- a/apps/desktop/src/components/workpanel/SideChatTab.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-import { useTranslation } from "react-i18next";
-import type { UiMessage } from "@pi-desktop/shared";
-import { ChatTranscript, TranscriptReadOnlyContext } from "../ChatTranscript";
-import { PermissionCard } from "../PermissionCard";
-import { AskToolCard } from "../AskToolCard";
-import { Button } from "../ui";
-import { useAppStore } from "../../stores/app-store";
-import { sideChatSendBlockReason } from "../../lib/side-chat";
-import { headAsk, queuedAskCount } from "../../lib/pending-asks";
-import { headPermission, sessionPermissions } from "../../lib/pending-permissions";
-
-const EMPTY_MESSAGES: UiMessage[] = [];
-
-/**
- * The docked side-chat surface (ADR message-quotes-and-side-chats / D-LOCAL-message-quotes).
- *
- * Before first Send the panel shows an anchored preview and a draft. After
- * creation it renders the child session's own live projection, so a follow-up
- * conversation streams, asks for permission, and can be stopped without making
- * the child the application's visible session. Closing the panel or promoting it
- * releases the renderer-only registration; the child session is durable and
- * stays in the sidebar, where it opens as an ordinary conversation.
- */
-export function SideChatTab({ sessionId }: { sessionId: string }) {
- const { t } = useTranslation();
- const messages = useAppStore(
- (s) => s.sideChatTranscripts[sessionId] ?? EMPTY_MESSAGES,
- );
- const isRunning = useAppStore((s) => s.runningSessions[sessionId] ?? false);
- const planningState = useAppStore((s) => s.planningStates[sessionId]);
- const pendingPermission = useAppStore((s) =>
- headPermission(s.pendingPermissions, sessionId),
- );
- const queuedPermissions = useAppStore((s) =>
- Math.max(0, sessionPermissions(s.pendingPermissions, sessionId).length - 1),
- );
- const pendingAsk = useAppStore((s) => headAsk(s.pendingAsks, sessionId));
- const queuedAsks = useAppStore((s) => queuedAskCount(s.pendingAsks, sessionId));
- const sendSideChatPrompt = useAppStore((s) => s.sendSideChatPrompt);
- const entry = useAppStore((s) => s.sideChats[sessionId]);
- const updateSideChatDraft = useAppStore((s) => s.updateSideChatDraft);
- const abortSession = useAppStore((s) => s.abortSession);
- const closeSideChat = useAppStore((s) => s.closeSideChat);
- const addSideChatReplyToMain = useAppStore((s) => s.addSideChatReplyToMain);
- const selectSession = useAppStore((s) => s.selectSession);
- const draft = entry?.draft ?? "";
- const sending = entry?.sending ?? false;
- const blockedReason = useAppStore((state) => sideChatSendBlockReason(
- state.sideChats[sessionId], state.sessions, state.runningSessions,
- ));
- const sendBlocked = Boolean(blockedReason);
-
- const send = async () => {
- const text = draft.trim();
- if (!text || sending || sendBlocked) return;
- await sendSideChatPrompt(sessionId);
- };
-
- const openAsConversation = async () => {
- if (entry?.pending || sending) return;
- // Release first: the promotion replaces the panel with the ordinary
- // conversation surface, including the full composer and prompt queue.
- closeSideChat(sessionId);
- await selectSession(sessionId);
- };
-
- return (
- <div className="side-chat" data-side-chat={sessionId}>
- <div className="side-chat-actions">
- <Button
- type="button"
- variant="secondary"
- size="sm"
- className="side-chat-action"
- data-side-chat-action="add-to-main"
- disabled={entry?.pending || !messages.some((message) => message.role === "assistant")}
- onClick={() => addSideChatReplyToMain(sessionId)}
- >
- {t("sideChat.addToMain")}
- </Button>
- <Button
- type="button"
- variant="secondary"
- size="sm"
- className="side-chat-action"
- data-side-chat-action="open-as-session"
- disabled={entry?.pending || sending}
- onClick={() => void openAsConversation()}
- >
- {t("sideChat.openAsSession")}
- </Button>
- </div>
- <div className="side-chat-thread">
- {/* A read-only projection: the child's rows must not offer the active
- session's Edit/Delete/Retry/Fork/Quote actions, and the panel owns the
- one permission card below, so the transcript renders content only. */}
- <TranscriptReadOnlyContext.Provider value>
- <ChatTranscript
- sessionId={sessionId}
- messages={messages}
- hasMoreBefore={false}
- isRunning={isRunning}
- pendingPermission={pendingPermission}
- queuedPermissions={queuedPermissions}
- askPending={Boolean(pendingAsk)}
- planningState={planningState}
- paneVisible
- />
- </TranscriptReadOnlyContext.Provider>
- </div>
- {/* The child asks its own questions; the card resolves that child's
- request id, so answering it here keeps the side chat moving. */}
- {pendingAsk ? (
- <AskToolCard request={pendingAsk} queued={queuedAsks} />
- ) : null}
- {entry?.error ? <div role="alert">{entry.error}</div> : null}
- <form
- className="side-chat-composer"
- onSubmit={(event) => {
- event.preventDefault();
- void send();
- }}
- >
- <textarea
- className="side-chat-input selectable"
- value={draft}
- rows={2}
- placeholder={t("sideChat.placeholder")}
- aria-label={t("sideChat.placeholder")}
- spellCheck={false}
- autoCorrect="off"
- autoCapitalize="off"
- onChange={(event) => updateSideChatDraft(sessionId, event.target.value)}
- onKeyDown={(event) => {
- // Same contract as the composer: Enter sends, Shift+Enter breaks the
- // line, and an in-flight IME composition owns Enter (D125).
- if (event.key !== "Enter" || event.shiftKey) return;
- if (event.nativeEvent.isComposing) return;
- event.preventDefault();
- void send();
- }}
- />
- <div className="side-chat-composer-row">
- <span className="side-chat-hint">
- {blockedReason
- ? t(blockedReason)
- : messages.length === 0
- ? t("sideChat.empty")
- : null}
- </span>
- {isRunning ? (
- <Button
- type="button"
- variant="secondary"
- size="sm"
- className="side-chat-action"
- data-side-chat-action="stop"
- onClick={() => void abortSession(sessionId)}
- >
- {t("chat.stopGenerating")}
- </Button>
- ) : null}
- <Button
- type="submit"
- variant="primary"
- size="sm"
- className="side-chat-action"
- disabled={!draft.trim() || sending || sendBlocked}
- >
- {t("chat.send")}
- </Button>
- </div>
- </form>
- {pendingPermission ? (
- <PermissionCard
- key={pendingPermission.requestId}
- permission={pendingPermission}
- queued={queuedPermissions}
- />
- ) : null}
- </div>
- );
-}
diff --git a/apps/desktop/src/components/workpanel/WorkPanel.tsx b/apps/desktop/src/components/workpanel/WorkPanel.tsx
index 58804f19d..ff81e0b42 100644
--- a/apps/desktop/src/components/workpanel/WorkPanel.tsx
+++ b/apps/desktop/src/components/workpanel/WorkPanel.tsx
@@ -26,7 +26,6 @@ import {
IconBot,
IconChevronLeft,
IconClose,
- IconChat,
IconDiff,
IconFileText,
IconPanelMaximize,
@@ -38,7 +37,6 @@ import { ReviewTab } from "./ReviewTab";
import { FilesTab } from "./FilesTab";
import { PluginViewTab } from "./PluginViewTab";
import { SubagentPanel } from "./SubagentPanel";
-import { SideChatTab } from "./SideChatTab";
import type { SubagentPanelSelection } from "../../lib/subagent-panel";
import {
MAIN_PANE_MIN_WIDTH,
@@ -47,14 +45,12 @@ import {
clampWorkPanelWidth,
workPanelLayout,
} from "../../lib/work-panel-resize";
-import { sideChatTabSessionId } from "../../lib/side-chat";
const TAB_ICONS = {
new: IconPlus,
review: IconDiff,
file: IconFileText,
plugin: IconPlug,
- sidechat: IconChat,
} as const;
type WorkPanelResizeState = {
@@ -87,9 +83,6 @@ function tabLabel(
// back to its id rather than leaving the tab blank until it closes.
return view?.title ?? tab.resource ?? t("panel.tabs.plugin");
}
- // The side-chat tab shows a conversation, so it reuses the side chat's own
- // label instead of inventing a second name for the same surface (D-LOCAL-message-quotes).
- if (tab.kind === "sidechat") return t("sideChat.title");
if (tab.kind === "new") return t("panel.new.title");
if (tab.kind !== "file") return t(`panel.tabs.${tab.kind}`);
const path = tab.resource ?? "";
@@ -626,25 +619,6 @@ export function WorkPanel({
</div>
);
})()}
- {/* A side chat docks the child session's conversation beside the main
- one. The child retains its renderer-owned transcript while another tab is visible. */}
- {!subagentPanel &&
- activeTab?.kind === "sidechat" &&
- (() => {
- const sessionId = sideChatTabSessionId(activeTab);
- if (!sessionId) return null;
- return (
- <div
- key={activeTab.id}
- id={`work-panel-surface-${activeTab.id}`}
- className="work-panel-tabpane"
- role="tabpanel"
- aria-labelledby={`work-panel-tab-${activeTab.id}`}
- >
- <SideChatTab sessionId={sessionId} />
- </div>
- );
- })()}
{!subagentPanel && (!activeTab || activeTab.kind === "new") && (
<div
className="work-panel-tabpane"
diff --git a/apps/desktop/src/features/chat/composer/ComposerStatus.tsx b/apps/desktop/src/features/chat/composer/ComposerStatus.tsx
index d55ec57e5..0ebe4369b 100644
--- a/apps/desktop/src/features/chat/composer/ComposerStatus.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerStatus.tsx
@@ -14,7 +14,6 @@ import {
type QueuedPrompt,
type QueuedPromptDirection,
} from "../../../lib/queued-prompts";
-import { requestTextWithoutAnnotations } from "../../../lib/response-annotations";
export type ComposerStatusProps = {
t: TFunction;
@@ -58,7 +57,7 @@ export function ComposerStatus({
>
{queuedPrompts.map((item) => {
const label =
- requestTextWithoutAnnotations(item.content).trim() ||
+ item.content.trim() ||
item.draft.fileReferences.map((reference) => reference.name).join(", ") ||
t("chat.queuedPromptEmpty");
const promoted = isPromotedQueuedPrompt(item);
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
index 27c2d1343..b976e341f 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
@@ -192,12 +192,7 @@ export function useComposerSubmit({
activeFileReferences,
);
const serializedContent = serializeComposerFileReferences(text, activeFileReferences);
- // Steering is text-only; saved annotations belong to the next send/queue.
- const state = useAppStore.getState();
- const annotationsPending = !steering && Boolean(
- state.activeSessionId && state.responseAnnotations[state.activeSessionId]?.length,
- );
- if (!serializedContent && !annotationsPending) return;
+ if (!serializedContent) return;
if (sendBlocked) {
if (pasting) showToast(t("chat.pasteInProgress"), { variant: "info" });
return;
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
index adea722f3..ea9d56df0 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
@@ -1,6 +1,5 @@
import {
memo,
- useContext,
useMemo,
useRef,
} from "react";
@@ -25,10 +24,6 @@ import {
collectDelegationTimings,
} from "../../../lib/subagent-topology";
import { useAppStore } from "../../../stores/app-store";
-import { TranscriptReadOnlyContext } from "./context";
-import { selectionMarkdownWithinRow } from "../../../lib/selection-quote";
-import { selectionAnnotationAnchorWithinRow } from "../../../lib/response-annotation-anchor";
-import { IconQuote, IconChat } from "../../../components/icons";
import { Markdown } from "../../../components/Markdown";
import { IconBranch, IconReview } from "../../../components/icons";
import { TooltipButton } from "../../../components/ui";
@@ -217,18 +212,6 @@ export const AssistantTurn = memo(function AssistantTurn({
const { t } = useTranslation();
const retryAssistantMessage = useAppStore((s) => s.retryAssistantMessage);
const forkAssistantMessage = useAppStore((s) => s.forkAssistantMessage);
- const annotateLabel = t("chat.annotate");
- const sideChatLabel = t("chat.startSideChat");
- const openSideChat = useAppStore((s) => s.openSideChat);
- const openResponseAnnotationEditor = useAppStore(
- (s) => s.openResponseAnnotationEditor,
- );
- const transcriptReadOnly = useContext(TranscriptReadOnlyContext);
- // The host refuses a fork while the source turn is still running, so the
- // affordance is disabled rather than silently doing nothing.
- const sessionRunning = useAppStore((s) =>
- s.activeSessionId ? s.runningSessions[s.activeSessionId] === true : false,
- );
const messages = assistantTurnMessages(entry);
const content = assistantTurnContent(entry);
const actionMessage = [...messages]
@@ -342,7 +325,7 @@ export const AssistantTurn = memo(function AssistantTurn({
responseOutputTokens={responseOutputTokens}
/>
) : null}
- {(content || hasError) && actionMessage && !transcriptReadOnly ? (
+ {(content || hasError) && actionMessage ? (
<div className="message-actions">
{complete ? (
<CopyButton text={content} label={t("chat.copy")} />
@@ -367,40 +350,6 @@ export const AssistantTurn = memo(function AssistantTurn({
<IconReview size={13} />
</TooltipButton>
) : null}
- {complete ? (
- <TooltipButton
- className="copy-btn icon"
- tooltip={annotateLabel}
- ariaLabel={annotateLabel}
- onPointerDown={(event) => event.preventDefault()}
- onClick={() => {
- // An annotation is a response concept (D-LOCAL-response-annotations): the selection
- // when there is one, the whole answer otherwise. The excerpt
- // is read before the editor takes focus. A turn without an
- // anchor has no row to annotate.
- if (!entry.anchorId) return;
- const selection = selectionMarkdownWithinRow(entry.anchorId);
- openResponseAnnotationEditor({
- messageId: entry.anchorId,
- text: selection || content,
- anchor: selectionAnnotationAnchorWithinRow(entry.anchorId),
- });
- }}
- >
- <IconQuote size={13} />
- </TooltipButton>
- ) : null}
- {complete ? (
- <TooltipButton
- className="copy-btn icon"
- tooltip={sideChatLabel}
- ariaLabel={sideChatLabel}
- disabled={sessionRunning}
- onClick={() => void openSideChat(actionMessage.id)}
- >
- <IconChat size={13} />
- </TooltipButton>
- ) : null}
</div>
) : null}
</div>
diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
index 2080426ad..5af204ca3 100644
--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
@@ -1,4 +1,4 @@
-import { memo, useContext } from "react";
+import { memo } from "react";
import { useTranslation } from "react-i18next";
import type { PlanningState, UiMessage } from "@pi-desktop/shared";
import { proposalKindForMode } from "@pi-desktop/shared";
@@ -16,9 +16,6 @@ import {
WorkingIndicator,
} from "./ActivityGroup";
import { TranscriptHistory, TranscriptTail } from "./AssistantTurn";
-import { TranscriptReadOnlyContext, useActiveSessionTitle } from "./context";
-import { SelectionQuoteButton } from "../../../components/SelectionQuoteButton";
-import { ResponseAnnotationOverlay } from "../../../components/ResponseAnnotationOverlay";
import { useTranscriptScroll } from "./hooks/useTranscriptScroll";
import type { TranscriptSearchTarget } from "../../../lib/transcript-reading";
import { TranscriptSearchContext } from "../../../lib/transcript-search-context";
@@ -67,8 +64,6 @@ export const ChatTranscript = memo(function ChatTranscript({
}) {
const { t } = useTranslation();
const transcriptRunning = isRunning && !readingWindow;
- const transcriptReadOnly = useContext(TranscriptReadOnlyContext);
- const sessionTitle = useActiveSessionTitle();
const latestTurnResult = useAppStore((state) =>
sessionId ? state.latestTurnResults[sessionId] : undefined,
);
@@ -109,7 +104,6 @@ export const ChatTranscript = memo(function ChatTranscript({
handleScroll,
revealEarlierHistory,
jumpToLatest,
- navigateAnnotation,
disclosureAnchorNotifier,
} = useTranscriptScroll({
sessionId,
@@ -198,14 +192,6 @@ export const ChatTranscript = memo(function ChatTranscript({
onRevealEarlier={revealEarlierHistory}
/>
) : null}
- {/* Quoting follows the selection: the row action at the end of a long
- * answer is the wrong end of the message to reach for (ADR message-quotes-and-side-chats / D-LOCAL-selection-overlay). */}
- {transcriptReadOnly || !paneVisible ? null : (
- <SelectionQuoteButton scrollRef={scrollRef} title={sessionTitle} />
- )}
- {!transcriptReadOnly && paneVisible && !veilCovering && sessionId ? (
- <ResponseAnnotationOverlay sessionId={sessionId} scrollRef={scrollRef} onNavigate={navigateAnnotation} />
- ) : null}
<div
className="thread-scroll"
ref={scrollRef}
@@ -256,7 +242,7 @@ export const ChatTranscript = memo(function ChatTranscript({
result={latestTurnResult}
/>
) : null}
- {pendingPermission && !transcriptReadOnly ? (
+ {pendingPermission ? (
<PermissionCard
key={pendingPermission.requestId}
permission={pendingPermission}
diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
index d15cbf9af..8ac4e2329 100644
--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
@@ -1,6 +1,5 @@
import {
memo,
- useContext,
useMemo,
useState,
} from "react";
@@ -17,10 +16,6 @@ import {
IconTrash,
} from "../../../components/icons";
import { TooltipButton } from "../../../components/ui";
-import { TranscriptReadOnlyContext, useActiveSessionTitle } from "./context";
-import { selectionMarkdownWithinRow } from "../../../lib/selection-quote";
-import { requestTextWithoutAnnotations } from "../../../lib/response-annotations";
-import { IconQuote, IconChat } from "../../../components/icons";
import { SessionMessageOrigin } from "./SessionMessageOrigin";
import {
CopyButton,
@@ -47,19 +42,14 @@ export const MessageRow = memo(function MessageRow({
const openFileRef = useOpenChatFileRef();
// Slash prompts are stored expanded; editing works on the typed form so the
// resent turn re-expands the template (D123).
- const editSeed = (editableUserMessage && message.command) || requestTextWithoutAnnotations(message.content || "");
+ const editSeed =
+ (editableUserMessage && message.command) || (message.content || "");
const [editing, setEditing] = useState(false);
const [editValue, setEditValue] = useState(editSeed);
const [retryingEdit, setRetryingEdit] = useState(false);
const copyLabel = t("chat.copy");
const editLabel = t("chat.editMessage");
const deleteLabel = t("chat.deleteMessage");
- const quoteLabel = t("chat.quote");
- const sideChatLabel = t("chat.startSideChat");
- const sessionTitle = useActiveSessionTitle();
- const openSideChat = useAppStore((s) => s.openSideChat);
- const quoteMessageIntoComposer = useAppStore((s) => s.quoteMessageIntoComposer);
- const transcriptReadOnly = useContext(TranscriptReadOnlyContext);
// Runtime chunks are already progressive. Rendering that source directly
// avoids a second per-frame state loop while Markdown memoizes stable blocks.
const displayed = message.content || "";
@@ -189,7 +179,7 @@ export const MessageRow = memo(function MessageRow({
{message.command}
</code>
) : (
- <LinkifiedText text={requestTextWithoutAnnotations(String(message.content || ""))} />
+ <LinkifiedText text={String(message.content || "")} />
)}
</div>
) : null}
@@ -201,7 +191,7 @@ export const MessageRow = memo(function MessageRow({
)}
</div>
) : null}
- {!editing && !transcriptReadOnly && (hasAnswer || showRevisionPager) ? (
+ {!editing && (hasAnswer || showRevisionPager) ? (
<div className="message-actions">
{showRevisionPager ? (
<div className="message-revision-pager" role="group" aria-label={t("chat.revisions")}>
@@ -264,33 +254,6 @@ export const MessageRow = memo(function MessageRow({
<IconTrash size={13} />
</TooltipButton>
) : null}
- <TooltipButton
- className="copy-btn icon"
- tooltip={quoteLabel}
- ariaLabel={quoteLabel}
- disabled={!editSeed}
- onClick={() =>
- quoteMessageIntoComposer({
- title: sessionTitle,
- text: editSeed,
- // The rendered selection is recovered as Markdown, so a quoted
- // formula keeps its TeX and a quoted table keeps its rows
- // (ADR message-quotes-and-side-chats / D-LOCAL-selection-overlay).
- selection: selectionMarkdownWithinRow(message.id),
- })
- }
- >
- <IconQuote size={13} />
- </TooltipButton>
- <TooltipButton
- className="copy-btn icon"
- tooltip={sideChatLabel}
- ariaLabel={sideChatLabel}
- disabled={isRunning}
- onClick={() => void openSideChat(message.id)}
- >
- <IconChat size={13} />
- </TooltipButton>
</div>
) : null}
</div>
diff --git a/apps/desktop/src/features/chat/transcript/context.ts b/apps/desktop/src/features/chat/transcript/context.ts
deleted file mode 100644
index 6dc4ca6f7..000000000
--- a/apps/desktop/src/features/chat/transcript/context.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { createContext } from "react";
-import { useAppStore } from "../../../stores/app-store";
-
-/**
- * Whether this transcript is a passive projection of another session (D-LOCAL-message-quotes).
- *
- * A docked side chat renders a real session that is not the application's active
- * one, but the row toolbars resolve against the active session — Delete would
- * re-page the visible conversation, Edit/Retry/Fork would address ids the parent
- * does not own, and the inline permission card would duplicate the panel's own.
- * A read-only projection therefore renders content only, and the panel owns every
- * control for its child.
- */
-export const TranscriptReadOnlyContext = createContext(false);
-
-/** Visible conversation title: the quote attribution and the side-chat source. */
-export function useActiveSessionTitle(): string {
- return useAppStore(
- (state) =>
- state.sessions.find((session) => session.id === state.activeSessionId)
- ?.title ?? "",
- );
-}
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
index c70d12281..ca9f4ebca 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
@@ -44,8 +44,6 @@ import type { TranscriptSearchTarget } from "../../../../lib/transcript-reading"
import { useTranscriptSearchFocus } from "../../../../hooks/use-transcript-search-focus";
import { useAppStore } from "../../../../stores/app-store";
-import type { ResponseAnnotation } from "../../../../lib/response-annotations";
-import { annotationRange, annotationRow } from "../../../../lib/response-annotation-anchor";
const HISTORY_REVEAL_THRESHOLD_PX = 120;
@@ -92,8 +90,6 @@ export function useTranscriptScroll({
const prependHeightRef = useRef<number | null>(null);
const [loadingOlder, setLoadingOlder] = useState(false);
const [showJump, setShowJump] = useState(false);
- const [pendingAnnotation, setPendingAnnotation] = useState<ResponseAnnotation | null>(null);
- const annotationPagesRef = useRef(new Set<number>());
// Steady-state cap on mounted history rows (D261). Grows when the user
// reaches the top of the window; reset per session below.
@@ -620,59 +616,6 @@ export function useTranscriptScroll({
);
const hasEarlierHistory = transcriptWindow.hiddenAbove > 0 || hasMoreBefore;
- const navigateAnnotation = useCallback((annotation: ResponseAnnotation) => {
- releaseDisclosureAnchor();
- cancelFollowScroll();
- pinnedRef.current = false;
- setShowJump(true);
- annotationPagesRef.current.clear();
- setPendingAnnotation(annotation);
- }, [cancelFollowScroll, releaseDisclosureAnchor]);
-
- // An annotation can precede the mounted window (or a reloaded history page).
- // Reveal its row before measuring, then scroll only this pane, not the window.
- useEffect(() => {
- if (!pendingAnnotation) return;
- if (!paneVisible || !sessionId ||
- !useAppStore.getState().responseAnnotations[sessionId]?.some((item) => item.id === pendingAnnotation.id)) {
- setPendingAnnotation(null);
- return;
- }
- const root = scrollRef.current;
- if (!root || hydrationBounded) return;
- const row = annotationRow(root, pendingAnnotation.messageId);
- if (row) {
- const range = annotationRange(row, pendingAnnotation.anchor);
- const rect = range?.getBoundingClientRect() ?? row.getBoundingClientRect();
- const dockTop = document.querySelector('[data-composer-dock="docked"]')?.getBoundingClientRect().top ?? window.innerHeight;
- const top = root.getBoundingClientRect().top;
- root.scrollTo({
- top: Math.max(0, root.scrollTop + rect.top - top - Math.max(24, (dockTop - top) / 3)),
- behavior: "auto",
- });
- lastScrollTopRef.current = root.scrollTop;
- setPendingAnnotation(null);
- return;
- }
- const index = allHistoryEntries.findIndex((entry) =>
- entry.kind === "assistant-turn" && entry.anchorId === pendingAnnotation.messageId);
- if (index >= 0) {
- // Keep each history reveal bounded, just like scrolling upward (D261).
- const frame = requestAnimationFrame(() => setWindowSize((size) =>
- Math.min(Math.max(size, allHistoryEntries.length - index),
- growTranscriptWindow(size, allHistoryEntries.length))));
- return () => cancelAnimationFrame(frame);
- }
- if (loadingOlder) return;
- if (!hasMoreBefore || !onLoadOlder || annotationPagesRef.current.has(messages.length)) {
- setPendingAnnotation(null);
- return;
- }
- annotationPagesRef.current.add(messages.length);
- setLoadingOlder(true);
- void onLoadOlder().catch(() => setPendingAnnotation(null))
- .finally(() => setLoadingOlder(false));
- }, [pendingAnnotation, paneVisible, hydrationBounded, allHistoryEntries, historyEntries, hasMoreBefore, loadingOlder, onLoadOlder, sessionId, messages.length]);
const revealEarlierHistory = useCallback(() => {
const el = scrollRef.current;
@@ -792,7 +735,6 @@ export function useTranscriptScroll({
revealEarlierHistory,
scrollToBottom,
jumpToLatest,
- navigateAnnotation,
disclosureAnchorNotifier,
};
}
diff --git a/apps/desktop/src/lib/chat-quotes.ts b/apps/desktop/src/lib/chat-quotes.ts
deleted file mode 100644
index 262eb0fb1..000000000
--- a/apps/desktop/src/lib/chat-quotes.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Message references ("quotes").
- *
- * A quote is plain draft text: the excerpt the user picked plus one attribution
- * line, inserted into the composer of the conversation they are looking at.
- * Quoting never sends, never creates a session, and writes nothing to the
- * transcript, so per-session draft retention and the smart-Stop restore path
- * keep working unchanged (ADR message-quotes-and-side-chats / D-LOCAL-message-quotes).
- */
-
-/** Longest excerpt a quote carries; longer text is cut and marked with an ellipsis. */
-export const MAX_QUOTE_CHARS = 2000;
-
-/**
- * The text a quote carries. A non-empty selection wins over the whole message,
- * so quoting a paragraph of a long answer stays a reference to that paragraph.
- */
-export function quoteExcerpt(
- messageText: string,
- selection = "",
- limit = MAX_QUOTE_CHARS,
-): string {
- const source = selection.trim() ? selection : messageText;
- const normalized = source.replace(/\r\n?/g, "\n").trim();
- if (normalized.length <= limit) return normalized;
- const cut = normalized.slice(0, limit);
- // Never cut between a surrogate pair: the tail would render as a lone glyph.
- const whole = /[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut;
- return `${whole.trimEnd()}…`;
-}
-
-/**
- * A Markdown blockquote of the excerpt followed by its attribution. The
- * attribution arrives already translated, which keeps this module free of i18n
- * and directly testable.
- */
-export function buildQuoteText(excerpt: string, attribution: string): string {
- const body = quoteExcerpt(excerpt)
- .split("\n")
- .map((line) => (line.trim() ? `> ${line}` : ">"))
- .join("\n");
- return `${body}\n\n${attribution}`;
-}
-
-/**
- * Put a quote into an existing draft without discarding what the user already
- * typed: quoting is an addition to the prompt, never a replacement of it.
- */
-export function appendQuoteToDraft(draftText: string, quote: string): string {
- const existing = draftText.replace(/\s+$/, "");
- return existing ? `${existing}\n\n${quote}` : quote;
-}
diff --git a/apps/desktop/src/lib/response-annotation-anchor.ts b/apps/desktop/src/lib/response-annotation-anchor.ts
deleted file mode 100644
index d1e9257ff..000000000
--- a/apps/desktop/src/lib/response-annotation-anchor.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { activeSelectionRange, expandRangeToWholeKatex, quotableRowFor } from "./selection-quote";
-
-/** Renderer-only offsets in the answer's text nodes, never in prompt payloads. */
-export type ResponseAnnotationAnchor = { start: number; end: number; exact: string };
-
-/** Resolve the original occurrence; relocate only when its text is unambiguous. */
-export function resolveAnnotationOffsets(text: string, anchor: ResponseAnnotationAnchor) {
- if (anchor.start >= 0 && anchor.end > anchor.start &&
- text.slice(anchor.start, anchor.end) === anchor.exact) {
- return { start: anchor.start, end: anchor.end };
- }
- if (!anchor.exact) return null;
- const start = text.indexOf(anchor.exact);
- if (start < 0 || text.indexOf(anchor.exact, start + 1) !== -1) return null;
- return { start, end: start + anchor.exact.length };
-}
-
-function answerTextNodes(row: Element): Text[] {
- const walker = row.ownerDocument.createTreeWalker(row, 4 /* SHOW_TEXT */);
- const nodes: Text[] = [];
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
- const parent = node.parentElement;
- if (!node.textContent || !parent?.closest(".prose-chat") ||
- parent.closest(".code-block-head, .katex-mathml, .response-annotation-marker, [data-annotation-layer]")) continue;
- nodes.push(node as Text);
- }
- return nodes;
-}
-
-export function captureAnnotationAnchor(row: Element, selection: Range): ResponseAnnotationAnchor | undefined {
- if (!row.contains(selection.startContainer) || !row.contains(selection.endContainer)) return;
- const range = expandRangeToWholeKatex(selection);
- const nodes = answerTextNodes(row);
- let offset = 0;
- let start = -1;
- let end = -1;
- for (const node of nodes) {
- if (range.intersectsNode(node)) {
- const from = node === range.startContainer ? range.startOffset : 0;
- const to = node === range.endContainer ? range.endOffset : node.length;
- if (to > from) {
- if (start < 0) start = offset + from;
- end = offset + to;
- }
- }
- offset += node.length;
- }
- if (start < 0 || end <= start) return;
- return { start, end, exact: nodes.map((node) => node.data).join("").slice(start, end) };
-}
-
-export function selectionAnnotationAnchorWithinRow(rowId: string): ResponseAnnotationAnchor | undefined {
- const range = activeSelectionRange();
- const row = range && quotableRowFor(range.startContainer);
- if (!range || !row || row.getAttribute("data-minimap-id") !== rowId) return;
- return captureAnnotationAnchor(row, range);
-}
-
-/** A failed resolution is deliberately a row-level fallback, not a guessed pass. */
-export function annotationRange(row: Element, anchor?: ResponseAnnotationAnchor): Range | null {
- if (!anchor) return null;
- const nodes = answerTextNodes(row);
- const offsets = resolveAnnotationOffsets(nodes.map((node) => node.data).join(""), anchor);
- if (!offsets) return null;
- const range = row.ownerDocument.createRange();
- let offset = 0;
- let started = false;
- for (const node of nodes) {
- const next = offset + node.length;
- if (!started && offsets.start < next) {
- range.setStart(node, offsets.start - offset);
- started = true;
- }
- if (started && offsets.end <= next) {
- range.setEnd(node, offsets.end - offset);
- return range;
- }
- offset = next;
- }
- return null;
-}
-
-export function annotationRow(root: Element, messageId: string): HTMLElement | undefined {
- return Array.from(root.querySelectorAll<HTMLElement>('[data-row-role="assistant"][data-minimap-id]'))
- .find((row) => row.dataset.minimapId === messageId);
-}
-
-/** Stack coincident badges without changing the answer's layout. */
-export function placeAnnotationBadges<T extends { top: number }>(badges: T[], top: number, bottom: number, size = 22) {
- let nextTop = top;
- return [...badges].sort((a, b) => a.top - b.top).map((badge) => {
- const placed = { ...badge, top: Math.max(nextTop, badge.top) };
- nextTop = placed.top + size + 3;
- return placed;
- }).filter((badge) => badge.top + size <= bottom);
-}
diff --git a/apps/desktop/src/lib/response-annotations.ts b/apps/desktop/src/lib/response-annotations.ts
deleted file mode 100644
index b438f33ac..000000000
--- a/apps/desktop/src/lib/response-annotations.ts
+++ /dev/null
@@ -1,297 +0,0 @@
-/**
- * Response annotations (ADR response-annotations / D-LOCAL-response-annotations, presentation amended by ADR floating-annotation-index).
- *
- * The reference implementation (ChatGPT desktop app) does not put a quoted
- * excerpt into the composer as text. Selecting text in a response and choosing
- * "Add to chat" opens a compact comment editor and attaches a **numbered
- * annotation** to that response when it saves: a floating index and source
- * badges identify the selections, and the next prompt carries the excerpts in a
- * structured block the model reads as `Annotation 1`, `Annotation 2`, … in
- * array order. Source badges never modify the answer DOM; the model's own
- * `:codex-annotation{index="N"}` citation is rendered separately.
- *
- * This module owns that contract: the editor's open/save transitions, the wire
- * block the prompt carries, the request text a stored prompt reduces back to,
- * and the inline marker geometry.
- */
-
-import type { ResponseAnnotationAnchor } from "./response-annotation-anchor";
-
-/** Heading the annotation block opens with, exactly as the reference sends it. */
-export const ANNOTATION_BLOCK_HEADING = "# Response annotations:";
-export const ANNOTATION_BLOCK_OPEN = "<response-annotations>";
-export const ANNOTATION_BLOCK_CLOSE = "</response-annotations>";
-/** Heading the user's own request is filed under, after the block. */
-export const ANNOTATION_REQUEST_HEADING = "## My request:";
-
-/**
- * The instruction sentence the block carries, verbatim from the reference. The
- * directive it asks for is the marker the renderer draws: an answered annotation
- * shows up as a numbered reference in the model's own answer, which is the only
- * place the reference marks one.
- */
-export const ANNOTATION_INSTRUCTION =
- "Each item contains text selected from an earlier assistant response and may include a user comment. Treat items as Annotation 1, Annotation 2, and so on in array order. Use every selection as context and address every comment. For every annotation you address, include its inline directive `:codex-annotation{index=\"N\"}`, where N is its one-based array position (for example, `:codex-annotation{index=\"1\"}`). Do not use unstructured annotation labels.";
-
-/** Longest excerpt one annotation carries, matching the quote cap (D-LOCAL-message-quotes). */
-export const MAX_ANNOTATION_CHARS = 2000;
-
-/** Inline marker syntax, matching the reference directive. */
-const MARKER_TOKEN = /:codex-annotation\{index="(\d+)"\}/g;
-
-export type ResponseAnnotation = {
- id: string;
- /** Assistant turn the annotation is anchored to; also its selection row id. */
- messageId: string;
- /** The excerpt, as Markdown, at the moment it was annotated. */
- text: string;
- /** Free-form user comment; empty until the user writes one in the editor. */
- annotation: string;
- createdAt: number;
- /** Optional renderer-only selected occurrence; never sent to the model. */
- anchor?: ResponseAnnotationAnchor;
-};
-
-/** Annotations of one session, in the order they were made. */
-export type ResponseAnnotationMap = Record<string, ResponseAnnotation[]>;
-
-export function responseAnnotation(input: {
- id: string;
- messageId: string;
- text: string;
- annotation?: string;
- createdAt?: number;
- anchor?: ResponseAnnotationAnchor;
-}): ResponseAnnotation {
- return {
- id: input.id,
- messageId: input.messageId,
- text: annotationExcerpt(input.text),
- annotation: (input.annotation ?? "").trim(),
- createdAt: input.createdAt ?? Date.now(),
- ...(input.anchor ? { anchor: input.anchor } : {}),
- };
-}
-
-/**
- * The comment editor's state (D-LOCAL-response-annotations): which annotation it edits, the excerpt it
- * was opened for, and the comment it was seeded with. `annotationId` is null
- * while the excerpt is still unattached. It is owned by the session it was
- * opened in, so a session switch cannot carry a half-written comment over.
- */
-export type ResponseAnnotationEditor = {
- sessionId: string;
- messageId: string;
- text: string;
- annotationId: string | null;
- comment: string;
- anchor?: ResponseAnnotationAnchor;
-};
-
-/** Missing offsets mean an unknown location, not proof of another occurrence. */
-function sameAnnotationSelection(
- annotation: ResponseAnnotation,
- input: Pick<ResponseAnnotationEditor, "messageId" | "text" | "anchor">,
-): boolean {
- return annotation.messageId === input.messageId && annotation.text === input.text &&
- (!annotation.anchor || !input.anchor ||
- (annotation.anchor.start === input.anchor.start && annotation.anchor.end === input.anchor.end));
-}
-
-/**
- * The editor to open for an excerpt, or null when there is none to open. An
- * explicit `annotationId` that no longer exists is stale — the annotation was
- * already sent or removed — and must not open a new one; a blank excerpt has
- * nothing to quote. Without an id, an excerpt that is already attached opens
- * that annotation for editing instead of a second one.
- */
-export function annotationEditorFor(
- annotations: readonly ResponseAnnotation[],
- input: {
- sessionId: string;
- messageId: string;
- text: string;
- annotationId?: string;
- anchor?: ResponseAnnotationAnchor;
- },
-): ResponseAnnotationEditor | null {
- if (!input.sessionId) return null;
- const excerpt = annotationExcerpt(input.text);
- const existing = input.annotationId
- ? annotations.find((annotation) => annotation.id === input.annotationId)
- : annotations.find((annotation) => sameAnnotationSelection(annotation, { ...input, text: excerpt }));
- if (existing) {
- return {
- sessionId: input.sessionId,
- messageId: existing.messageId,
- text: existing.text,
- annotationId: existing.id,
- comment: existing.annotation,
- ...(existing.anchor ? { anchor: existing.anchor } : {}),
- };
- }
- // A stale id, or an excerpt with nothing to quote, has no editor to open.
- if (input.annotationId || !excerpt) return null;
- return {
- sessionId: input.sessionId,
- messageId: input.messageId,
- text: excerpt,
- annotationId: null,
- comment: "",
- ...(input.anchor ? { anchor: input.anchor } : {}),
- };
-}
-
-/**
- * The annotation list a save produces, or null when the save changes nothing.
- * An edit whose target was already sent or removed is dropped rather than
- * recreated, the same excerpt is never attached twice, and re-saving the same
- * comment is a no-op. A save with no comment still attaches the excerpt, so
- * Add to chat works with and without a comment.
- */
-export function applyAnnotationComment(
- annotations: readonly ResponseAnnotation[],
- editor: ResponseAnnotationEditor,
- comment: string,
- id: string,
- createdAt = Date.now(),
-): ResponseAnnotation[] | null {
- const nextComment = String(comment ?? "").trim();
- if (editor.annotationId) {
- const index = annotations.findIndex(
- (annotation) => annotation.id === editor.annotationId,
- );
- if (index === -1) return null;
- if (annotations[index].annotation === nextComment) return null;
- const next = [...annotations];
- next[index] = { ...next[index], annotation: nextComment };
- return next;
- }
- if (annotations.some((annotation) => sameAnnotationSelection(annotation, editor))) {
- return null;
- }
- return [
- ...annotations,
- responseAnnotation({
- id,
- messageId: editor.messageId,
- text: editor.text,
- annotation: nextComment,
- createdAt,
- anchor: editor.anchor,
- }),
- ];
-}
-
-/** Wire shape of one annotation inside the block, as the reference sends it. */
-function annotationPayload(annotation: ResponseAnnotation): {
- text: string;
- annotation: string;
- source: { messageId: string };
-} {
- return {
- text: annotation.text,
- annotation: annotation.annotation,
- source: { messageId: annotation.messageId },
- };
-}
-
-/**
- * The prompt a session's annotations turn the composer text into: the block
- * first, then the request under its own heading, so the model can tell the
- * excerpts from the instruction.
- */
-export function responseAnnotationPrompt(
- content: string,
- annotations: readonly ResponseAnnotation[],
-): string {
- if (annotations.length === 0) return content;
- return [
- ANNOTATION_BLOCK_HEADING,
- ANNOTATION_INSTRUCTION,
- ANNOTATION_BLOCK_OPEN,
- JSON.stringify(annotations.map(annotationPayload)),
- ANNOTATION_BLOCK_CLOSE,
- "",
- ANNOTATION_REQUEST_HEADING,
- content,
- ].join("\n");
-}
-
-/**
- * The request a stored prompt reduces back to. A prompt the host echoes back
- * carries the block; the transcript, the composer's edit seed, and the minimap
- * excerpt all show the request only.
- */
-export function requestTextWithoutAnnotations(prompt: string): string {
- const text = String(prompt ?? "");
- if (!text.startsWith(`${ANNOTATION_BLOCK_HEADING}\n`)) return text;
- const heading = `\n${ANNOTATION_REQUEST_HEADING}\n`;
- const index = text.lastIndexOf(heading);
- if (index === -1) {
- // Main trims prompt text; an annotation-only request ends at the heading.
- return text.endsWith(`\n${ANNOTATION_REQUEST_HEADING}`) ? "" : text;
- }
- return text.slice(index + heading.length);
-}
-
-/** Cap one excerpt, never cutting between the halves of a surrogate pair. */
-export function annotationExcerpt(
- text: string,
- limit = MAX_ANNOTATION_CHARS,
-): string {
- const normalized = String(text ?? "")
- .replace(/\r\n?/g, "\n")
- .trim();
- if (normalized.length <= limit) return normalized;
- const cut = normalized.slice(0, limit);
- const whole = /[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut;
- return `${whole.trimEnd()}…`;
-}
-
-/* ---------- inline markers ---------- */
-
-export const ANNOTATION_MARKER_CLASS = "response-annotation-marker";
-
-/**
- * The token that stands in for one numbered marker. It is the reference's own
- * directive syntax, so a model that cites an annotation renders as a marker
- * instead of leaving the raw directive in the answer.
- */
-export function annotationMarkerToken(index: number): string {
- return `:codex-annotation{index="${index}"}`;
-}
-
-/** One piece of a text node split around its marker tokens. */
-export type AnnotationMarkerSegment =
- | { kind: "text"; value: string }
- | { kind: "marker"; index: number };
-
-/**
- * Split rendered text around its marker tokens, so the markdown pass can turn
- * each marker into a numbered element instead of leaving the raw directive in
- * the answer.
- */
-export function splitAnnotationMarkerTokens(
- text: string,
-): AnnotationMarkerSegment[] {
- const value = String(text ?? "");
- const segments: AnnotationMarkerSegment[] = [];
- let cursor = 0;
- for (const match of value.matchAll(MARKER_TOKEN)) {
- const at = match.index ?? 0;
- if (at > cursor) segments.push({ kind: "text", value: value.slice(cursor, at) });
- segments.push({ kind: "marker", index: Number(match[1]) });
- cursor = at + match[0].length;
- }
- if (cursor < value.length) segments.push({ kind: "text", value: value.slice(cursor) });
- return segments;
-}
-
-/** Replace marker tokens with the given text (used by plain-text surfaces). */
-export function stripAnnotationMarkerTokens(
- text: string,
- replacement = "",
-): string {
- return String(text ?? "").replace(MARKER_TOKEN, replacement);
-}
diff --git a/apps/desktop/src/lib/selection-quote.ts b/apps/desktop/src/lib/selection-quote.ts
deleted file mode 100644
index 8849a2f26..000000000
--- a/apps/desktop/src/lib/selection-quote.ts
+++ /dev/null
@@ -1,580 +0,0 @@
-/**
- * Selection overlay geometry and selection → Markdown recovery for message
- * quotes (ADR message-quotes-and-side-chats / D-LOCAL-selection-overlay).
- *
- * Mirrors the ChatGPT desktop app's selected-text overlay: one pill floats
- * *above* the selection, horizontally centered on it, inside the bounds of the
- * scroll container it lives in (and above the docked composer), and it follows
- * the selection while the thread scrolls instead of disappearing.
- *
- * A selection inside a rendered answer is DOM, not source text: KaTeX paints
- * two parallel trees per formula, the highlighter splits one fence into a span
- * per token, and a table renders as cells. Handing that DOM to the composer
- * duplicates every formula, flattens every table, and turns code into
- * decorations, so a clone of the range is reduced back to Markdown — `$…$` TeX,
- * fenced code, one line per table row — before it becomes draft text.
- *
- * The overlay and the per-message action row both quote through
- * {@link serializeSelectionMarkdown}: one recovery path, not two spellings of
- * the same mistake.
- */
-
-/** Gap between the selection and the floating pill. */
-export const SELECTION_QUOTE_GAP = 8;
-/** Smallest distance the pill keeps from the bounds it is clamped into. */
-export const SELECTION_QUOTE_MARGIN = 8;
-/** Markdown fences start at three backticks and grow past the longest run. */
-export const SELECTION_QUOTE_MIN_FENCE = 3;
-
-/** The transcript row attribute a quotable selection anchors to (D-LOCAL-message-quotes). */
-export const QUOTABLE_ROW_ATTRIBUTE = "data-minimap-id";
-/** Row role attribute: annotations belong to assistant turns (D-LOCAL-response-annotations). */
-export const ROW_ROLE_ATTRIBUTE = "data-row-role";
-/** The role value that takes response annotations instead of a draft quote. */
-export const ANNOTATABLE_ROW_ROLE = "assistant";
-/** The docked composer's own element, which the pill must stay above. */
-export const COMPOSER_DOCK_SELECTOR = '[data-composer-dock="docked"]';
-
-const KATEX_TEX_SELECTOR = 'annotation[encoding="application/x-tex"]';
-const OVERFLOW_VALUES = new Set(["auto", "clip", "hidden", "overlay", "scroll"]);
-
-/** Viewport rectangle, structurally typed so geometry stays testable. */
-export type SelectionQuoteRect = {
- left: number;
- top: number;
- right: number;
- bottom: number;
- width: number;
- height: number;
-};
-
-/** The box the pill has to stay inside. */
-export type SelectionQuoteBounds = {
- left: number;
- top: number;
- right: number;
- bottom: number;
-};
-
-/** Everything the pill needs to render and act on one selection. */
-export type SelectionQuoteTarget = {
- /** Transcript row the selection belongs to; the quote and fork anchor. */
- rowAnchorId: string;
- /** The selection, already reduced to the Markdown the composer receives. */
- markdown: string;
- /** Visible part of the selection, in viewport coordinates. */
- anchor: SelectionQuoteRect;
- /** Bounds the pill is clamped into. */
- bounds: SelectionQuoteBounds;
- /**
- * Whether the row is an assistant turn. Annotations are a response concept
- * (D-LOCAL-response-annotations): a selection in the user's own message still quotes into the draft.
- */
- annotatable: boolean;
-};
-
-/* ---------- pure helpers ---------- */
-
-function longestRun(text: string, character: string): number {
- let longest = 0;
- let current = 0;
- for (const value of text) {
- if (value === character) {
- current += 1;
- if (current > longest) longest = current;
- } else {
- current = 0;
- }
- }
- return longest;
-}
-
-/**
- * A fence long enough to contain `text`, so quoting a snippet that itself
- * contains backticks cannot break out of the block.
- */
-export function codeFenceFor(
- text: string,
- minimum = SELECTION_QUOTE_MIN_FENCE,
-): string {
- return "`".repeat(Math.max(minimum, longestRun(text, "`") + 1));
-}
-
-/**
- * Collapse the whitespace the rendered DOM adds back to source-like text:
- * markup indentation, non-breaking spaces, soft hyphens, and the blank lines
- * that separating blocks introduce.
- */
-export function normalizeSelectionMarkdown(value: string): string {
- return String(value ?? "")
- .replace(/\r\n?/g, "\n")
- .replace(/\u00a0/g, " ")
- .replace(/[\u200b\ufeff]/g, "")
- .split("\n")
- .map((line) => line.replace(/[ \t]+$/g, ""))
- .join("\n")
- .replace(/\n[ \t]+\n/g, "\n\n")
- .replace(/\n{3,}/g, "\n\n")
- .trim();
-}
-
-/**
- * The part of `rect` that is inside `bounds`, or null when they do not overlap.
- * A selection scrolled half out of its container is anchored to the half that
- * is still on screen.
- */
-export function intersectSelectionQuoteRect(
- rect: SelectionQuoteRect,
- bounds: SelectionQuoteBounds,
-): SelectionQuoteRect | null {
- const left = Math.max(rect.left, bounds.left);
- const top = Math.max(rect.top, bounds.top);
- const right = Math.min(rect.right, bounds.right);
- const bottom = Math.min(rect.bottom, bounds.bottom);
- if (left >= right || top >= bottom) return null;
- return { left, top, right, bottom, width: right - left, height: bottom - top };
-}
-
-/**
- * Place the pill above the selection, centered on it, then clamp it into the
- * bounds. Only the horizontal axis can collide (the pill is narrow and near the
- * top of the selection), so a selection against the right edge slides left
- * instead of leaving the container. Returns the measured width cap too, so a
- * narrow panel cannot push the pill out of its own bounds.
- */
-export function placeSelectionQuote({
- anchor,
- size,
- bounds,
- margin = SELECTION_QUOTE_MARGIN,
- gap = SELECTION_QUOTE_GAP,
-}: {
- anchor: SelectionQuoteRect;
- size: { width: number; height: number };
- bounds: SelectionQuoteBounds;
- margin?: number;
- gap?: number;
-}): { top: number; left: number; maxWidth: number } {
- const maxWidth = Math.max(0, bounds.right - bounds.left - margin * 2);
- const width = Math.min(size.width, maxWidth);
- const maximumLeft = Math.max(bounds.left + margin, bounds.right - margin - width);
- const left = Math.min(
- Math.max(anchor.left + anchor.width / 2 - width / 2, bounds.left + margin),
- maximumLeft,
- );
- const maximumTop = Math.max(bounds.top + margin, bounds.bottom - size.height);
- const top = Math.min(
- Math.max(anchor.top - gap - size.height, bounds.top + margin),
- maximumTop,
- );
- return { top, left, maxWidth };
-}
-
-/* ---------- DOM reduction ---------- */
-
-function replaceWithText(node: Element, text: string, doc: Document): void {
- node.replaceWith(doc.createTextNode(text));
-}
-
-/**
- * A formula is one unit: KaTeX's MathML tree and its visual tree are two
- * renderings of the same source, and copying both duplicates the expression.
- * The TeX annotation is the source, so the whole formula is replaced by it —
- * `$…$` inline, `$$…$$` for a display block.
- */
-function replaceKatex(wrapper: Element, doc: Document): void {
- for (const katex of Array.from(wrapper.querySelectorAll(".katex"))) {
- const tex = katex.querySelector(KATEX_TEX_SELECTOR)?.textContent?.trim();
- const isDisplay = Boolean(katex.closest(".katex-display"));
- if (tex) {
- replaceWithText(katex, isDisplay ? `\n$$\n${tex}\n$$\n` : `$${tex}$`, doc);
- continue;
- }
- // Valid KaTeX always carries the annotation; keep one rendering if not.
- const fallback =
- katex.querySelector(".katex-html")?.textContent ?? katex.textContent ?? "";
- replaceWithText(katex, fallback, doc);
- }
-}
-
-function fencedBlock(code: string, language: string): string {
- const fence = codeFenceFor(code);
- return `\n${fence}${language}\n${code.replace(/\n$/, "")}\n${fence}\n`;
-}
-
-function replaceCodeBlocks(wrapper: Element, doc: Document): void {
- for (const block of Array.from(wrapper.querySelectorAll(".code-block"))) {
- const language = (block.querySelector(".code-block-lang")?.textContent ?? "")
- .trim()
- .replace(/[^A-Za-z0-9_+.-]/g, "");
- const code = block.querySelector("pre code")?.textContent ?? "";
- replaceWithText(block, fencedBlock(code, language), doc);
- }
- // A `pre` outside the app's code-block wrapper (or one reached on its own) is
- // still code, and quoting it line by line would read as prose.
- for (const pre of Array.from(wrapper.querySelectorAll("pre"))) {
- const code = pre.querySelector("code")?.textContent ?? pre.textContent ?? "";
- replaceWithText(pre, fencedBlock(code, ""), doc);
- }
-}
-
-function replaceInlineCode(wrapper: Element, doc: Document): void {
- for (const code of Array.from(wrapper.querySelectorAll("code"))) {
- if (code.closest("pre")) continue;
- const value = code.textContent ?? "";
- const fence = codeFenceFor(value, 1);
- replaceWithText(code, `${fence}${value}${fence}`, doc);
- }
-}
-
-function replaceTaskCheckboxes(wrapper: Element, doc: Document): void {
- for (const input of Array.from(
- wrapper.querySelectorAll('input[type="checkbox"]'),
- )) {
- replaceWithText(input, (input as HTMLInputElement).checked ? "[x] " : "[ ] ", doc);
- }
-}
-
-/**
- * Drop transcript chrome, and unwrap the rest of the controls: a file-reference
- * chip renders its code inside a button, so removing buttons outright would
- * delete the text the user selected.
- */
-function removeChrome(wrapper: Element): void {
- for (const node of Array.from(
- wrapper.querySelectorAll(
- [
- ".message-actions",
- ".code-block-head",
- // Annotation markers are references, not text the user picked (D-LOCAL-response-annotations).
- ".response-annotation-marker",
- "script",
- "style",
- "noscript",
- "template",
- "[hidden]",
- '[aria-hidden="true"]',
- ".sr-only",
- ].join(","),
- ),
- )) {
- node.remove();
- }
- for (const button of Array.from(wrapper.querySelectorAll("button"))) {
- button.replaceWith(...Array.from(button.childNodes));
- }
-}
-
-/**
- * A row is the smallest unit that carries meaning across the visual column
- * split, so each row becomes one `a | b` line.
- */
-function replaceTables(wrapper: Element, doc: Document): void {
- for (const row of Array.from(wrapper.querySelectorAll("tr"))) {
- const cells = Array.from(row.querySelectorAll(":scope > th, :scope > td"));
- if (cells.length === 0) continue;
- const value = cells
- .map((cell) => (cell.textContent ?? "").trim().replace(/\s*\n\s*/g, " "))
- .join(" | ");
- replaceWithText(row, `${value}\n`, doc);
- }
-}
-
-function replaceLists(wrapper: Element, doc: Document): void {
- // Innermost first: a nested item must become text before its parent reads it.
- for (const item of Array.from(wrapper.querySelectorAll("li")).reverse()) {
- const parent = item.parentElement;
- let prefix = "- ";
- if (parent?.tagName?.toLowerCase() === "ol") {
- const siblings = Array.from(parent.children).filter(
- (child) => child.tagName?.toLowerCase() === "li",
- );
- const start = Number.parseInt(parent.getAttribute("start") ?? "1", 10) || 1;
- prefix = `${start + Math.max(0, siblings.indexOf(item))}. `;
- }
- replaceWithText(item, `${prefix}${(item.textContent ?? "").trim()}\n`, doc);
- }
-}
-
-function replaceHeadings(wrapper: Element, doc: Document): void {
- for (let level = 1; level <= 6; level += 1) {
- for (const heading of Array.from(wrapper.querySelectorAll(`h${level}`))) {
- replaceWithText(
- heading,
- `\n${"#".repeat(level)} ${(heading.textContent ?? "").trim()}\n`,
- doc,
- );
- }
- }
-}
-
-function addBlockBoundaries(wrapper: Element, doc: Document): void {
- for (const br of Array.from(wrapper.querySelectorAll("br"))) {
- replaceWithText(br, "\n", doc);
- }
- for (const rule of Array.from(wrapper.querySelectorAll("hr"))) {
- replaceWithText(rule, "\n---\n", doc);
- }
- for (const block of Array.from(
- wrapper.querySelectorAll("p, pre, blockquote, section, article, div"),
- )) {
- block.before(doc.createTextNode("\n"));
- block.after(doc.createTextNode("\n"));
- }
-}
-
-/**
- * Expand a range that starts or ends inside a formula to the whole formula:
- * half of a TeX expression is not a quote, and KaTeX's two trees make a partial
- * cut ambiguous anyway. Both boundaries only ever move within the row the
- * selection already covers, so no extra containment check is needed.
- */
-export function expandRangeToWholeKatex(range: Range): Range {
- const expanded = range.cloneRange();
- const boundaryFor = (node: Node | null): Element | null => {
- const element =
- node?.nodeType === 1 ? (node as Element) : (node?.parentElement ?? null);
- const katex = element?.closest?.(".katex") ?? null;
- return katex?.closest?.(".katex-display") ?? katex;
- };
- const start = boundaryFor(expanded.startContainer);
- const end = boundaryFor(expanded.endContainer);
- if (start) expanded.setStartBefore(start);
- if (end) expanded.setEndAfter(end);
- return expanded;
-}
-
-/**
- * The Markdown a rendered selection stands for. Returns an empty string when
- * there is nothing quotable, which every caller treats as "keep the pill
- * hidden".
- */
-export function serializeSelectionMarkdown(range: Range | null): string {
- if (!range) return "";
- const ownerDocument =
- range.commonAncestorContainer?.ownerDocument ??
- (range.commonAncestorContainer?.nodeType === 9
- ? (range.commonAncestorContainer as unknown as Document)
- : null) ??
- (typeof document === "undefined" ? null : document);
- if (!ownerDocument) return "";
-
- const wrapper = ownerDocument.createElement("div");
- wrapper.append(expandRangeToWholeKatex(range).cloneContents());
-
- // Order matters: formulas and code are reduced before chrome is dropped and
- // before generic block boundaries are inserted, or their own markup would be
- // flattened into the text the reduction is looking for.
- replaceKatex(wrapper, ownerDocument);
- replaceCodeBlocks(wrapper, ownerDocument);
- replaceInlineCode(wrapper, ownerDocument);
- replaceTaskCheckboxes(wrapper, ownerDocument);
- removeChrome(wrapper);
- replaceTables(wrapper, ownerDocument);
- replaceLists(wrapper, ownerDocument);
- replaceHeadings(wrapper, ownerDocument);
- addBlockBoundaries(wrapper, ownerDocument);
-
- return normalizeSelectionMarkdown(wrapper.textContent ?? "");
-}
-
-/* ---------- live selection ---------- */
-
-/** The transcript row a node sits in, or null when the selection is elsewhere. */
-export function quotableRowFor(node: Node | null | undefined): Element | null {
- const element =
- node?.nodeType === 1 ? (node as Element) : (node?.parentElement ?? null);
- return element?.closest?.(`[${QUOTABLE_ROW_ATTRIBUTE}]`) ?? null;
-}
-
-/** Whether a transcript row is an assistant turn (the annotatable kind). */
-export function isAnnotatableRow(row: Element | null): boolean {
- return row?.getAttribute?.(ROW_ROLE_ATTRIBUTE) === ANNOTATABLE_ROW_ROLE;
-}
-
-/** The document selection, when it is a non-empty text range. */
-export function activeSelectionRange(): Range | null {
- if (typeof window === "undefined") return null;
- const selection = window.getSelection();
- if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
- return null;
- }
- const range = selection.getRangeAt(0);
- return range.toString().trim() ? range : null;
-}
-
-/**
- * Keep a range inside one element: a drag that leaves the row must not pull the
- * next row's text into the quote.
- */
-export function clampRangeToElement(range: Range, element: Element): Range {
- const clamped = range.cloneRange();
- const contents = range.startContainer.ownerDocument!.createRange();
- contents.selectNodeContents(element);
- if (
- !element.contains(clamped.startContainer) ||
- clamped.compareBoundaryPoints(Range.START_TO_START, contents) < 0
- ) {
- clamped.setStart(contents.startContainer, contents.startOffset);
- }
- if (
- !element.contains(clamped.endContainer) ||
- clamped.compareBoundaryPoints(Range.END_TO_END, contents) > 0
- ) {
- clamped.setEnd(contents.endContainer, contents.endOffset);
- }
- return clamped;
-}
-
-/**
- * The visible band the pill may use: every scrollable ancestor's rect (the
- * transcript scroller is one) intersected with the viewport, and capped by the
- * docked composer — which floats over the transcript, so the scroller's own
- * bottom edge is not the visible bottom.
- */
-export function selectionQuoteBounds({
- element,
- viewport,
- bottomBoundaryTop,
-}: {
- element: Element | null;
- viewport: { width: number; height: number };
- bottomBoundaryTop?: number | null;
-}): SelectionQuoteBounds | null {
- const bounds: SelectionQuoteBounds = {
- left: 0,
- top: 0,
- right: viewport.width,
- bottom:
- typeof bottomBoundaryTop === "number"
- ? Math.min(viewport.height, bottomBoundaryTop)
- : viewport.height,
- };
- const ownerDocument = element?.ownerDocument;
- const view = ownerDocument?.defaultView;
- let node: Element | null = element;
- while (node && node !== ownerDocument?.body && node !== ownerDocument?.documentElement) {
- const style = view?.getComputedStyle?.(node);
- // `overflow: hidden` on a decorative wrapper clips the selection too, so it
- // counts the same as a real scroll container.
- const clipsX = (style?.overflowX ?? "").split(/\s+/).some((v) => OVERFLOW_VALUES.has(v));
- const clipsY = (style?.overflowY ?? "").split(/\s+/).some((v) => OVERFLOW_VALUES.has(v));
- if (clipsX || clipsY) {
- const rect = node.getBoundingClientRect();
- if (clipsY) {
- bounds.top = Math.max(bounds.top, rect.top);
- bounds.bottom = Math.min(bounds.bottom, rect.bottom);
- }
- if (clipsX) {
- bounds.left = Math.max(bounds.left, rect.left);
- bounds.right = Math.min(bounds.right, rect.right);
- }
- if (bounds.right <= bounds.left || bounds.bottom <= bounds.top) return null;
- }
- node = node.parentElement;
- }
- return bounds.bottom <= bounds.top ? null : bounds;
-}
-
-/**
- * Where the pill anchors: the selection's first client rect that is still
- * visible inside the bounds (a multi-line selection anchors to its top line),
- * falling back to the visible part of the whole bounding box.
- */
-export function selectionQuoteAnchor({
- range,
- element,
- bounds,
-}: {
- range: Range;
- element: Element;
- bounds: SelectionQuoteBounds;
-}): SelectionQuoteRect | null {
- const rowRect = element.getBoundingClientRect();
- const rects = Array.from(range.getClientRects()).filter(
- (rect) => rect.width > 0 && rect.height > 0,
- );
- for (const rect of rects) {
- const visible = intersectSelectionQuoteRect(rect, bounds);
- if (!visible) continue;
- if (rects.length > 1 || intersectSelectionQuoteRect(visible, rowRect)) {
- return visible;
- }
- }
- const bounding = range.getBoundingClientRect();
- const visibleBounding = intersectSelectionQuoteRect(bounding, bounds);
- if (visibleBounding && intersectSelectionQuoteRect(visibleBounding, rowRect)) {
- return visibleBounding;
- }
- if (rects.length > 0 || bounding.width > 0 || bounding.height > 0) return null;
- const rowVisible = intersectSelectionQuoteRect(rowRect, bounds);
- return rowVisible;
-}
-
-/**
- * Everything the pill renders from, or null when the selection is not one it
- * should own: no selection, a selection outside this transcript, a selection
- * that spans two rows, or an empty excerpt.
- */
-export function selectionQuoteTarget({
- scrollRoot,
- bottomBoundaryTop,
- viewport = {
- width: typeof window === "undefined" ? 0 : window.innerWidth,
- height: typeof window === "undefined" ? 0 : window.innerHeight,
- },
-}: {
- scrollRoot: Element | null;
- bottomBoundaryTop?: number | null;
- viewport?: { width: number; height: number };
-}): SelectionQuoteTarget | null {
- const live = activeSelectionRange();
- if (!live || !scrollRoot) return null;
-
- const startRow = quotableRowFor(live.startContainer);
- // Both ends must sit in the same row: a drag that crosses rows has no single
- // message to attribute, and the reference implementation refuses it too.
- if (!startRow || startRow !== quotableRowFor(live.endContainer)) return null;
- if (!scrollRoot.contains(startRow)) return null;
-
- const rowAnchorId = startRow.getAttribute(QUOTABLE_ROW_ATTRIBUTE) ?? "";
- if (!rowAnchorId) return null;
-
- const range = clampRangeToElement(live, startRow);
- const markdown = serializeSelectionMarkdown(range);
- if (!markdown) return null;
-
- const bounds = selectionQuoteBounds({
- element: startRow,
- viewport,
- bottomBoundaryTop,
- });
- if (!bounds) return null;
- const anchor = selectionQuoteAnchor({ range, element: startRow, bounds });
- if (!anchor) return null;
-
- return {
- rowAnchorId,
- markdown,
- anchor,
- bounds,
- annotatable: isAnnotatableRow(startRow),
- };
-}
-
-/**
- * The Markdown of the current selection when it is inside `rowAnchorId`, and an
- * empty string otherwise — a selection in another row must not be attributed to
- * the message whose action row was clicked.
- */
-export function selectionMarkdownWithinRow(
- rowAnchorId: string,
- container: Element | Document | null = null,
-): string {
- const range = activeSelectionRange();
- if (!range) return "";
- const row = quotableRowFor(range.startContainer);
- if (!row || row.getAttribute(QUOTABLE_ROW_ATTRIBUTE) !== rowAnchorId) return "";
- if (container && !(container as Element).contains?.(row)) return "";
- return serializeSelectionMarkdown(range);
-}
diff --git a/apps/desktop/src/lib/side-chat.ts b/apps/desktop/src/lib/side-chat.ts
deleted file mode 100644
index 51cba5778..000000000
--- a/apps/desktop/src/lib/side-chat.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-/**
- * Side chats: a follow-up conversation opened from a message.
- *
- * A side chat starts as a renderer-only draft. First Send materializes an
- * ordinary forked child session on the host, and the renderer
- * keeps it out of the visible conversation: it is registered against its parent
- * session and shown in the docked work panel, so the main transcript, its
- * composer draft, and its run state are never replaced (ADR message-quotes-and-side-chats / D-LOCAL-message-quotes).
- */
-import type { SessionSummary } from "@pi-desktop/shared";
-import type { WorkPanelTab } from "./work-panel-tabs";
-
-export type SideChatEntry = {
- /** Renderer draft id until first Send; then the durable child session id. */
- sessionId: string;
- /** Conversation the side chat was opened from. */
- parentSessionId: string;
- /** Child session title, shown by the panel and kept in the sidebar. */
- title: string;
- /** Message the fork was anchored at, when it was opened from one. */
- anchorMessageId?: string;
- createdAt: number;
- pending?: boolean;
- draft?: string;
- sending?: boolean;
- error?: string;
-};
-
-export type SideChatMap = Record<string, SideChatEntry>;
-
-/** Tab ids are session-keyed so re-opening a side chat reuses its tab. */
-export const SIDE_CHAT_TAB_PREFIX = "sidechat:";
-
-export function sideChatWorkPanelTab(sessionId: string): WorkPanelTab {
- return {
- id: `${SIDE_CHAT_TAB_PREFIX}${sessionId}`,
- kind: "sidechat",
- resource: sessionId,
- };
-}
-
-export function isSideChatTab(
- tab: WorkPanelTab | null | undefined,
-): tab is WorkPanelTab {
- return Boolean(tab) && tab?.kind === "sidechat";
-}
-
-/** The child session a side-chat tab shows, or null for any other tab. */
-export function sideChatTabSessionId(
- tab: WorkPanelTab | null | undefined,
-): string | null {
- if (!isSideChatTab(tab)) return null;
- const resource = (tab?.resource ?? "").trim();
- return resource ? resource : null;
-}
-
-export function sideChatEntry(
- input: Omit<SideChatEntry, "createdAt"> & { createdAt?: number },
-): SideChatEntry {
- return {
- sessionId: input.sessionId,
- parentSessionId: input.parentSessionId,
- title: input.title,
- ...(input.anchorMessageId ? { anchorMessageId: input.anchorMessageId } : {}),
- createdAt: input.createdAt ?? Date.now(),
- ...(input.pending ? { pending: true } : {}),
- ...(input.draft !== undefined ? { draft: input.draft } : {}),
- };
-}
-
-/** Register (or re-register) a child session as a side chat of its parent. */
-export function registerSideChat(
- chats: SideChatMap,
- entry: SideChatEntry,
-): SideChatMap {
- return { ...chats, [entry.sessionId]: entry };
-}
-
-/** Drop one side chat. An unknown id returns the same map, not a fresh copy. */
-export function removeSideChat(chats: SideChatMap, sessionId: string): SideChatMap {
- if (!chats[sessionId]) return chats;
- const next = { ...chats };
- delete next[sessionId];
- return next;
-}
-
-/**
- * Drop the side chats that must not outlive a deleted session: the session
- * itself, and every side chat reachable only through it.
- */
-export function removeSideChatsForSessions(
- chats: SideChatMap,
- sessionIds: readonly string[],
-): SideChatMap {
- const doomed = new Set(sessionIds);
- let kept = Object.values(chats);
- // Releasing cascades down the parent chain: a side chat opened from a released
- // session is no longer reachable from any conversation either, so dropping only
- // the first generation would strand children nobody can see or close.
- for (;;) {
- const next = kept.filter(
- (entry) =>
- !doomed.has(entry.sessionId) && !doomed.has(entry.parentSessionId),
- );
- if (next.length === kept.length) break;
- for (const entry of kept) {
- if (!next.includes(entry)) doomed.add(entry.sessionId);
- }
- kept = next;
- }
- if (kept.length === Object.keys(chats).length) return chats;
- return Object.fromEntries(kept.map((entry) => [entry.sessionId, entry]));
-}
-
-export function sideChatEntryForSession(
- chats: SideChatMap,
- sessionId: string,
-): SideChatEntry | undefined {
- return chats[sessionId];
-}
-
-/** Side chats opened from one conversation, newest first. */
-export function sideChatsForParent(
- chats: SideChatMap,
- parentSessionId: string | undefined,
-): SideChatEntry[] {
- if (!parentSessionId) return [];
- return Object.values(chats)
- .filter((entry) => entry.parentSessionId === parentSessionId)
- .sort((a, b) => b.createdAt - a.createdAt);
-}
-
-export function sideChatSessionIds(chats: SideChatMap): string[] {
- return Object.keys(chats);
-}
-
-/** One send gate for both the panel and programmatic submissions. */
-export function sideChatSendBlockReason(
- entry: SideChatEntry | undefined,
- sessions: readonly Pick<SessionSummary, "id" | "readOnlyReason">[],
- runningSessions: Readonly<Record<string, boolean>>,
-): "errors.noActiveSession" | "sideChat.parentBusy" | "sideChat.readOnly" | undefined {
- if (!entry) return "errors.noActiveSession";
- const ownerId = entry.pending ? entry.parentSessionId : entry.sessionId;
- const owner = sessions.find((session) => session.id === ownerId);
- if (!owner) return "errors.noActiveSession";
- if (entry.pending && (runningSessions[ownerId] || owner.readOnlyReason === "busy")) {
- return "sideChat.parentBusy";
- }
- if (owner.readOnlyReason && owner.readOnlyReason !== "busy") {
- return "sideChat.readOnly";
- }
- // Existing children retain their queue/Stop behavior. Native busy sends are
- // rejected with the existing explanation in sendPrompt.
- return undefined;
-}
diff --git a/apps/desktop/src/lib/work-panel-tabs.ts b/apps/desktop/src/lib/work-panel-tabs.ts
index 918c0efa2..153598e5a 100644
--- a/apps/desktop/src/lib/work-panel-tabs.ts
+++ b/apps/desktop/src/lib/work-panel-tabs.ts
@@ -2,13 +2,7 @@ export type WorkPanelTabKind =
| "new"
| "review"
| "file"
- | "plugin"
- /**
- * A follow-up conversation opened from a message. The tab id is
- * `sidechat:<childSessionId>` and the resource is that child session, so the
- * panel shows a real session without making it the visible one (D-LOCAL-message-quotes).
- */
- | "sidechat";
+ | "plugin";
export type WorkPanelTab = {
id: string;
@@ -164,7 +158,7 @@ export function isKnownWorkPanelTab(tab: WorkPanelTab): boolean {
return (
Boolean(tab) &&
(tab.kind === "new" || tab.kind === "review" ||
- tab.kind === "file" || tab.kind === "plugin" || tab.kind === "sidechat")
+ tab.kind === "file" || tab.kind === "plugin")
);
}
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index 8f02aab47..3d54a80e9 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -101,8 +101,6 @@ export type DraftSessionConfiguration = {
permissionMode?: PermissionMode;
};
-import type { SideChatMap } from "../lib/side-chat";
-import type { ResponseAnnotationEditor, ResponseAnnotationMap } from "../lib/response-annotations";
export type AppState = {
ready: boolean;
@@ -351,62 +349,6 @@ export type AppState = {
/** Toggle the selected subagent detail. */
toggleSubagentPanel: (delegationId: string) => void;
closeSubagentPanel: () => void;
- /**
- * Side chats opened from messages, keyed by their child session id. The child
- * is a real forked session on the host; this map is what keeps it out of the
- * visible conversation and inside the docked panel (D-LOCAL-message-quotes).
- */
- sideChats: SideChatMap;
- /** Live transcript of each registered side chat, fed by the agent event stream. */
- sideChatTranscripts: Record<string, UiMessage[]>;
- /**
- * Numbered annotations the user attached to assistant turns, keyed by the
- * session that owns them. They are prompt attachments, not draft text: the
- * next prompt carries them as a block and the send consumes them
- * (ADR response-annotations / D-LOCAL-response-annotations).
- */
- responseAnnotations: ResponseAnnotationMap;
- /**
- * The comment editor's state (D-LOCAL-response-annotations); null while it is closed. It is owned by
- * the session it was opened in and holds the excerpt snapshot the selection
- * collapsed into.
- */
- responseAnnotationEditor: ResponseAnnotationEditor | null;
- /** Append text to the visible conversation's draft without sending it. */
- appendComposerDraftText: (text: string) => void;
- /** Open the comment editor for one assistant turn's excerpt. */
- openResponseAnnotationEditor: (input: {
- messageId: string;
- text: string;
- /** Existing annotation to edit; omitted while the excerpt is unattached. */
- annotationId?: string;
- anchor?: ResponseAnnotationEditor["anchor"];
- }) => void;
- /** Save the editor's comment and close it; a stale target is dropped. */
- saveResponseAnnotationEditor: (comment: string) => void;
- /** Close the editor without saving its comment. */
- closeResponseAnnotationEditor: () => void;
- /** Drop one annotation from the visible session. */
- removeResponseAnnotation: (id: string) => void;
- /** Drop every annotation of the visible session. */
- clearResponseAnnotations: () => void;
- /** Quote one message, or a selection inside it, into the composer draft. */
- quoteMessageIntoComposer: (input: {
- /** Source title used by the attribution line. */
- title: string;
- /** Full message text; a non-blank selection wins over it. */
- text: string;
- /** Text the user selected inside the message, when there is one. */
- selection?: string;
- }) => void;
- /** Open a renderer-only side-chat draft; resolves to its panel id. */
- openSideChat: (messageId: string, quote?: string) => Promise<string | null>;
- updateSideChatDraft: (id: string, text: string) => void;
- sendSideChatPrompt: (id: string) => Promise<boolean>;
- /** Release a side chat, keeping its durable child session. */
- closeSideChat: (sessionId: string) => void;
- /** Quote a side chat's newest answer into the main conversation's draft. */
- addSideChatReplyToMain: (sessionId: string) => void;
/** Abort one session's running turn, visible or not. */
abortSession: (sessionId: string) => Promise<void>;
openWorkPanel: () => void;
diff --git a/apps/desktop/src/stores/app-store.ts b/apps/desktop/src/stores/app-store.ts
index 8c69d87e5..a1db40214 100644
--- a/apps/desktop/src/stores/app-store.ts
+++ b/apps/desktop/src/stores/app-store.ts
@@ -172,8 +172,6 @@ import type {
ToastOptions,
ToastVariant,
} from "./app-state";
-import { createAnnotationSlice } from "./slices/annotation-slice";
-import { createSideChatSlice } from "./slices/side-chat-slice";
import { createSessionSlice } from "./slices/session-slice";
import { createQueueSlice } from "./slices/queue-slice";
import { createTranscriptSlice } from "./slices/transcript-slice";
@@ -720,8 +718,6 @@ export const useAppStore = create<AppState>((set, get) => {
}
},
- ...createAnnotationSlice({ get, set }),
- ...createSideChatSlice({ get, set, commitForkedSession, withoutRecordKey }),
...createWorkPanelSlice({
get,
set,
diff --git a/apps/desktop/src/stores/runtime/session-runtime.ts b/apps/desktop/src/stores/runtime/session-runtime.ts
index a37407871..a9ec8684e 100644
--- a/apps/desktop/src/stores/runtime/session-runtime.ts
+++ b/apps/desktop/src/stores/runtime/session-runtime.ts
@@ -82,7 +82,6 @@ export type SessionRuntime = {
insertOptimisticUserMessage: (sessionId: string, message: UiMessage) => void;
retractOptimisticUserMessage: (sessionId: string, message: UiMessage) => void;
cacheBackgroundTranscriptEvent: (envelope: AgentEventEnvelope) => void;
- projectSideChatEvent: (envelope: AgentEventEnvelope) => void;
mergeSessionConfiguration: (
current: SessionConfiguration | undefined,
next: SessionConfiguration,
@@ -217,14 +216,6 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime
function insertOptimisticUserMessage(sessionId: string, message: UiMessage): void {
const state = get();
- if (state.sideChatTranscripts[sessionId]) {
- set((current) => ({
- sideChatTranscripts: {
- ...current.sideChatTranscripts,
- [sessionId]: upsertLiveSessionMessage(current.sideChatTranscripts[sessionId] ?? [], message),
- },
- }));
- }
if (state.activeSessionId === sessionId) {
set((current) => ({
messages: upsertLiveSessionMessage(current.messages, message),
@@ -242,14 +233,6 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime
function retractOptimisticUserMessage(sessionId: string, message: UiMessage): void {
const state = get();
- if (state.sideChatTranscripts[sessionId]?.includes(message)) {
- set((current) => ({
- sideChatTranscripts: {
- ...current.sideChatTranscripts,
- [sessionId]: removeLiveSessionMessage(current.sideChatTranscripts[sessionId] ?? [], message.id),
- },
- }));
- }
if (state.activeSessionId === sessionId) {
set((current) =>
current.messages.includes(message)
@@ -364,17 +347,6 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime
return next;
}
- function projectSideChatEvent(envelope: AgentEventEnvelope): void {
- const state = get();
- if (!state.sideChats[envelope.sessionId]) return;
- const current = state.sideChatTranscripts[envelope.sessionId] ?? [];
- const next = projectTranscriptEvent(current, envelope);
- if (next === current) return;
- set((state) => ({
- sideChatTranscripts: { ...state.sideChatTranscripts, [envelope.sessionId]: next },
- }));
- }
-
function cacheBackgroundTranscriptEvent(envelope: AgentEventEnvelope): void {
const { sessionId } = envelope;
const state = get();
@@ -445,7 +417,6 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime
insertOptimisticUserMessage,
retractOptimisticUserMessage,
cacheBackgroundTranscriptEvent,
- projectSideChatEvent,
mergeSessionConfiguration: (current, next) => {
if (!current) return next;
const merged: Record<string, unknown> = { ...current };
diff --git a/apps/desktop/src/stores/slices/annotation-slice.ts b/apps/desktop/src/stores/slices/annotation-slice.ts
deleted file mode 100644
index 1d440c798..000000000
--- a/apps/desktop/src/stores/slices/annotation-slice.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import i18n from "i18next";
-import type { AppState } from "../app-state";
-import type { StoreAccess } from "./types";
-import { draftKeyForSession, readComposerDraft } from "../../lib/composer-draft-cache";
-import { appendQuoteToDraft, buildQuoteText, quoteExcerpt } from "../../lib/chat-quotes";
-import { annotationEditorFor, applyAnnotationComment } from "../../lib/response-annotations";
-
-export function createAnnotationSlice({ get, set }: StoreAccess): Pick<AppState,
- "appendComposerDraftText" | "openResponseAnnotationEditor" | "saveResponseAnnotationEditor" | "closeResponseAnnotationEditor" | "removeResponseAnnotation" | "clearResponseAnnotations" | "quoteMessageIntoComposer"> {
- return {
- appendComposerDraftText: (text) => {
- const sessionId = get().activeSessionId;
- if (!sessionId || !text) return;
- // Read the live draft so a quote adds to what the user already typed. The
- // composer applies this prefill for its own session and then clears it (D209).
- const draft = readComposerDraft(draftKeyForSession(sessionId));
- set({
- composerPrefill: {
- sessionId,
- text: appendQuoteToDraft(draft?.text ?? "", text),
- fileReferences: draft?.fileReferences ?? [],
- },
- });
- },
-
- openResponseAnnotationEditor: ({ messageId, text, annotationId, anchor }) => {
- const sessionId = get().activeSessionId;
- if (!sessionId) return;
- const current = get().responseAnnotations[sessionId] ?? [];
- // An excerpt that is already attached reopens its own annotation for
- // editing. The excerpt is snapshotted here, before focus moves into the
- // editor and collapses the selection it came from.
- set({
- responseAnnotationEditor: annotationEditorFor(current, {
- sessionId,
- messageId,
- text,
- annotationId,
- anchor,
- }),
- });
- },
-
- saveResponseAnnotationEditor: (comment) => {
- const editor = get().responseAnnotationEditor;
- if (!editor) return;
- const current = get().responseAnnotations[editor.sessionId] ?? [];
- const next = applyAnnotationComment(
- current,
- editor,
- comment,
- crypto.randomUUID(),
- );
- set((state) => {
- // A save whose target was already sent or removed changes nothing; it
- // must not recreate the annotation.
- if (!next) return { responseAnnotationEditor: null };
- return {
- responseAnnotations: {
- ...state.responseAnnotations,
- [editor.sessionId]: next,
- },
- responseAnnotationEditor: null,
- };
- });
- },
-
- closeResponseAnnotationEditor: () => {
- if (!get().responseAnnotationEditor) return;
- set({ responseAnnotationEditor: null });
- },
-
- removeResponseAnnotation: (id) => {
- const sessionId = get().activeSessionId;
- if (!sessionId) return;
- const current = get().responseAnnotations[sessionId] ?? [];
- const next = current.filter((annotation) => annotation.id !== id);
- if (next.length === current.length) return;
- set((state) => {
- const responseAnnotations = { ...state.responseAnnotations };
- if (next.length === 0) delete responseAnnotations[sessionId];
- else responseAnnotations[sessionId] = next;
- return { responseAnnotations };
- });
- },
-
- clearResponseAnnotations: () => {
- const sessionId = get().activeSessionId;
- if (!sessionId || !get().responseAnnotations[sessionId]) return;
- set((state) => {
- const responseAnnotations = { ...state.responseAnnotations };
- delete responseAnnotations[sessionId];
- return { responseAnnotations };
- });
- },
-
- quoteMessageIntoComposer: ({ title, text, selection }) => {
- if (!get().activeSessionId) return;
- const excerpt = quoteExcerpt(text, selection ?? "");
- if (!excerpt) return;
- get().appendComposerDraftText(
- buildQuoteText(excerpt, i18n.t("chat.quoteSource", { title })),
- );
- },
-
- };
-}
diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.ts
index 02cd1dcf9..88f62453e 100644
--- a/apps/desktop/src/stores/slices/events-slice.ts
+++ b/apps/desktop/src/stores/slices/events-slice.ts
@@ -185,23 +185,12 @@ export function createEventsSlice({
));
set((state) => ({
...(state.activeSessionId === sessionId ? { messages: reconcile(state.messages) } : {}),
- // Native side-chat children reconcile their optimistic row in the
- // panel projection too; the durable entry is the only canonical row.
- ...(state.sideChatTranscripts?.[sessionId]
- ? {
- sideChatTranscripts: {
- ...state.sideChatTranscripts,
- [sessionId]: reconcile(state.sideChatTranscripts[sessionId]),
- },
- }
- : {}),
retainedTranscripts: state.retainedTranscripts[sessionId]
? { ...state.retainedTranscripts, [sessionId]: reconcile(state.retainedTranscripts[sessionId]) }
: state.retainedTranscripts,
}));
return;
}
- runtime.projectSideChatEvent(envelope);
if (event.type === "message_end" && event.replacesMessageId) {
// Exact native stream re-key: the durable SDK entry replaces its own
// provisional row in the caches a reselect can paint from, while a
@@ -433,28 +422,6 @@ export function createEventsSlice({
} else if (event.type === "agent_end") {
void get().refreshSessions();
void triggerAutoTitleSummarization(envelope.sessionId);
- } else if (event.type === "error") {
- // A running child turn can fail before its first assistant row. The
- // panel is not the visible conversation, so surface it in the child
- // projection and as a toast instead of a silent draft restore.
- const childRows = get().sideChatTranscripts[envelope.sessionId];
- if (get().sideChats[envelope.sessionId] && childRows) {
- const errorRow = assistantErrorMessage(event.error);
- set((state) => ({
- sideChatTranscripts: {
- ...state.sideChatTranscripts,
- [envelope.sessionId]: [
- ...state.sideChatTranscripts[envelope.sessionId],
- errorRow,
- ],
- },
- }));
- const cached = runtime.sessionTranscriptCache.get(envelope.sessionId);
- if (cached) {
- runtime.cacheSessionTranscript(envelope.sessionId, [...cached, errorRow]);
- }
- get().showToast(event.error.message, { variant: "error" });
- }
} else if (event.type === "planning_state") {
void get().refreshSessions();
}
diff --git a/apps/desktop/src/stores/slices/initial-state.ts b/apps/desktop/src/stores/slices/initial-state.ts
index e9e580101..bd1f40d95 100644
--- a/apps/desktop/src/stores/slices/initial-state.ts
+++ b/apps/desktop/src/stores/slices/initial-state.ts
@@ -48,10 +48,6 @@ export function createInitialState(): AppStateData {
workPanelContexts: {},
workPanelWidth: initialWorkPanelWidth,
workPanelFileRequest: null,
- sideChats: {},
- sideChatTranscripts: {},
- responseAnnotations: {},
- responseAnnotationEditor: null,
projectSort: initialSidebarPreferences.projectSort,
messages: [],
retainedSessionIds: [],
diff --git a/apps/desktop/src/stores/slices/project-slice.ts b/apps/desktop/src/stores/slices/project-slice.ts
index 04259f784..bb6222f40 100644
--- a/apps/desktop/src/stores/slices/project-slice.ts
+++ b/apps/desktop/src/stores/slices/project-slice.ts
@@ -1,5 +1,3 @@
-import { removeSideChatsForSessions, sideChatSessionIds, sideChatWorkPanelTab } from "../../lib/side-chat";
-import type { WorkPanelTab } from "../../lib/work-panel-tabs";
import i18n from "i18next";
import type {
ProjectWorkspace,
@@ -532,63 +530,6 @@ export function createProjectSlice({
{ get, set, runtime, manualSessionTitles, withoutRecordKey },
id,
);
- // A side chat is renderer-owned state spanning two sessions: deleting either
- // the child or the parent releases it, together with every side chat opened
- // from it. The child session itself is deleted through its own sidebar row,
- // so this only drops the panel projection (D-LOCAL-message-quotes).
- set((state) => {
- const sideChats = removeSideChatsForSessions(state.sideChats, [id]);
- if (sideChats === state.sideChats) return {};
- const released = sideChatSessionIds(state.sideChats).filter(
- (sessionId) => !sideChats[sessionId],
- );
- const sideChatTranscripts = { ...state.sideChatTranscripts };
- for (const sessionId of released) delete sideChatTranscripts[sessionId];
- // A released side chat's tab outlives its session in every panel context
- // that still lists it, and a dead tab would offer a live composer for a
- // deleted session, so the tabs are stripped with the registration.
- const releasedTabIds = new Set(
- released.map((sessionId) => sideChatWorkPanelTab(sessionId).id),
- );
- const stripTabs = (tabs: WorkPanelTab[]) =>
- tabs.filter((tab) => !releasedTabIds.has(tab.id));
- const workPanelTabs = stripTabs(state.workPanelTabs);
- const activeTabReleased = Boolean(
- state.activeWorkPanelTabId &&
- releasedTabIds.has(state.activeWorkPanelTabId),
- );
- const workPanelContexts = Object.fromEntries(
- Object.entries(state.workPanelContexts).map(
- ([contextSessionId, context]) => {
- const tabs = stripTabs(context.tabs);
- if (tabs.length === context.tabs.length) {
- return [contextSessionId, context];
- }
- const activeTabId =
- context.activeTabId && releasedTabIds.has(context.activeTabId)
- ? tabs.at(-1)?.id ?? null
- : context.activeTabId;
- return [
- contextSessionId,
- { ...context, tabs, activeTabId, open: activeTabId ? context.open : false },
- ];
- },
- ),
- );
- return {
- sideChats,
- sideChatTranscripts,
- workPanelTabs,
- workPanelContexts,
- activeWorkPanelTabId: activeTabReleased
- ? workPanelTabs.at(-1)?.id ?? null
- : state.activeWorkPanelTabId,
- workPanelOpen:
- activeTabReleased && workPanelTabs.length === 0
- ? false
- : state.workPanelOpen,
- };
- });
persistCurrentSidebar(get);
await get().refreshSessions();
},
diff --git a/apps/desktop/src/stores/slices/queue-slice.ts b/apps/desktop/src/stores/slices/queue-slice.ts
index be015bcdf..d4efd4cac 100644
--- a/apps/desktop/src/stores/slices/queue-slice.ts
+++ b/apps/desktop/src/stores/slices/queue-slice.ts
@@ -1,4 +1,3 @@
-import { responseAnnotationPrompt } from "../../lib/response-annotations";
import i18n from "i18next";
import type {
AgentQueueChangedEvent,
@@ -356,20 +355,6 @@ export function createQueueSlice({
}
if (!sessionId) throw new Error(i18n.t("errors.noActiveSession"));
if (get().pendingPlans[sessionId]?.status === "pending") return false;
- // Capture this session's immutable annotation objects before awaiting the host.
- // Only accepted, unchanged objects are consumed; edits/new attachments survive.
- const annotationSessionId = sessionId;
- const annotations = get().responseAnnotations[annotationSessionId] ?? [];
- const outgoing = responseAnnotationPrompt(content, annotations);
- const consumeAnnotations = () => set((state) => {
- const current = state.responseAnnotations[annotationSessionId] ?? [];
- const remaining = current.filter((item) => !annotations.includes(item));
- if (remaining.length === current.length) return {};
- const responseAnnotations = { ...state.responseAnnotations };
- if (remaining.length) responseAnnotations[annotationSessionId] = remaining;
- else delete responseAnnotations[annotationSessionId];
- return { responseAnnotations };
- });
if (get().runningSessions[sessionId]) {
// Native Pi children have no Desktop prompt queue. Reject the send
// here so the caller restores the draft instead of round-tripping a
@@ -381,8 +366,7 @@ export function createQueueSlice({
get().showToast(i18n.t("chat.nativeSessionBusy"), { variant: "info" });
return false;
}
- const accepted = await get().enqueuePrompt(outgoing, draft, sessionId);
- if (accepted) consumeAnnotations();
+ const accepted = await get().enqueuePrompt(content, draft, sessionId);
return accepted;
}
const startedIn = sessionId;
@@ -448,12 +432,11 @@ export function createQueueSlice({
}
await api.prompt({
sessionId,
- content: outgoing,
+ content,
messageId: optimisticMessage.id,
viewingSessionId: viewingSessionIdForPrompt(get(), sessionId),
attachments: draft ? promptAttachmentsFromDraft(draft.fileReferences) : [],
});
- consumeAnnotations();
const submitted = runtime.submittedComposerDrafts.get(startedIn);
if (submitted?.abortResolution && (await submitted.abortResolution)) {
return false;
@@ -463,10 +446,8 @@ export function createQueueSlice({
runtime.submittedComposerDrafts.delete(startedIn);
runtime.retractOptimisticUserMessage(startedIn, optimisticMessage);
const messageError = messageErrorFromUnknown(error);
- const sideChatChild = Boolean(get().sideChats[startedIn]);
const errorRow = assistantErrorMessage(messageError);
set((state) => {
- const childRows = state.sideChatTranscripts[startedIn];
return {
isRunning:
state.activeSessionId === startedIn ? false : state.isRunning,
@@ -483,37 +464,14 @@ export function createQueueSlice({
sessionOutcomes: { ...state.sessionOutcomes, [startedIn]: "failed" },
...(state.activeSessionId === startedIn
? { messages: [...state.messages, errorRow] }
- : sideChatChild && childRows
- ? {
- sideChatTranscripts: {
- ...state.sideChatTranscripts,
- [startedIn]: [...childRows, errorRow],
- },
- }
- : {}),
+ : {}),
};
});
- if (sideChatChild && get().activeSessionId !== startedIn) {
- // The panel is not the visible conversation: surface the failure in
- // the child projection and as a toast instead of the main transcript.
- const cached = runtime.sessionTranscriptCache.get(startedIn);
- if (cached) {
- runtime.cacheSessionTranscript(startedIn, [...cached, errorRow]);
- }
- get().showToast(messageError.message, { variant: "error" });
- }
return false;
}
} catch (error) {
// Keep sendPrompt's Promise<boolean> contract so the composer can
// restore a draft cleared before submission, even on unexpected setup errors.
- const target = requestedSessionId ?? get().activeSessionId;
- if (target && get().sideChats[target]) {
- get().showToast(
- error instanceof Error ? error.message : String(error),
- { variant: "error" },
- );
- }
return false;
} finally {
pendingSubmissions.delete(submissionKey);
diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.ts
index 591a737da..7af59e84c 100644
--- a/apps/desktop/src/stores/slices/session-slice.ts
+++ b/apps/desktop/src/stores/slices/session-slice.ts
@@ -112,6 +112,7 @@ export function createSessionSlice({
| "forkSession"
| "forkAssistantMessage"
| "configureActiveSession"
+ | "abortSession"
> {
const refreshSessionList = createRefreshCoordinator(async () => {
const result = await api.listSessions();
@@ -587,5 +588,19 @@ export function createSessionSlice({
},
}));
},
+
+ /** Abort one session's running turn, whether or not it is the visible one. */
+ abortSession: async (sessionId) => {
+ if (!sessionId) return;
+ try {
+ await api.abort(sessionId);
+ } finally {
+ set((state) => ({
+ isRunning:
+ state.activeSessionId === sessionId ? false : state.isRunning,
+ runningSessions: { ...state.runningSessions, [sessionId]: false },
+ }));
+ }
+ },
};
}
diff --git a/apps/desktop/src/stores/slices/side-chat-slice.ts b/apps/desktop/src/stores/slices/side-chat-slice.ts
deleted file mode 100644
index 62f1d25e4..000000000
--- a/apps/desktop/src/stores/slices/side-chat-slice.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-import i18n from "i18next";
-import type { AppState } from "../app-state";
-import type { StoreAccess } from "./types";
-import { api } from "../../lib/api";
-import { forkedSessionMessages } from "../../lib/session-fork";
-import { sideChatSendBlockReason, registerSideChat, removeSideChat, sideChatEntry, sideChatWorkPanelTab, sideChatsForParent } from "../../lib/side-chat";
-import type { SessionSliceDependencies } from "./session-slice";
-
-export function createSideChatSlice({ get, set, commitForkedSession, withoutRecordKey }: StoreAccess &
- Pick<SessionSliceDependencies, "commitForkedSession" | "withoutRecordKey">): Pick<AppState,
- "openSideChat" | "updateSideChatDraft" | "sendSideChatPrompt" | "closeSideChat" | "addSideChatReplyToMain" | "abortSession"> {
- const sends = new Map<string, Promise<boolean>>();
- const updateEntry = (id: string, patch: Partial<AppState["sideChats"][string]>) => {
- set((state) => state.sideChats[id] ? {
- sideChats: { ...state.sideChats, [id]: { ...state.sideChats[id], ...patch } },
- } : {});
- };
- return {
- openSideChat: async (messageId, quote) => {
- const state = get();
- const parentSessionId = state.activeSessionId;
- if (!parentSessionId) return null;
- const index = state.messages.findIndex((message) => message.id === messageId);
- const parent = state.sessions.find((session) => session.id === parentSessionId);
- if (index < 0 || !parent || state.runningSessions[parentSessionId]) return null;
- const existing = sideChatsForParent(state.sideChats, parentSessionId).find(
- (chat) => chat.anchorMessageId === messageId,
- );
- const id = existing?.sessionId ?? `side-draft:${crypto.randomUUID()}`;
- const prefill = quote ? `${quote.split("\n").map((line) => `> ${line}`).join("\n")}\n\n` : "";
- if (existing) {
- if (prefill) updateEntry(id, { draft: [existing.draft, prefill].filter(Boolean).join("\n\n") });
- } else {
- const sourceTitle = parent.title.trim() || i18n.t("chat.untitledTask");
- set((current) => ({
- sideChats: registerSideChat(current.sideChats, sideChatEntry({
- sessionId: id,
- parentSessionId,
- anchorMessageId: messageId,
- title: i18n.t("sideChat.sessionTitle", { title: sourceTitle }),
- pending: true,
- draft: prefill,
- })),
- sideChatTranscripts: {
- ...current.sideChatTranscripts,
- [id]: state.messages.slice(0, index + 1),
- },
- }));
- }
- get().openWorkPanelTabForSession(parentSessionId, sideChatWorkPanelTab(id));
- return id;
- },
- updateSideChatDraft: (id, text) => updateEntry(id, { draft: text }),
- sendSideChatPrompt: async (id) => {
- const inFlight = sends.get(id);
- if (inFlight) return inFlight;
- const entry = get().sideChats[id];
- const text = entry?.draft?.trim();
- if (!entry || !text || entry.sending) return false;
- const blocked = sideChatSendBlockReason(entry, get().sessions, get().runningSessions);
- if (blocked) {
- get().showToast(i18n.t(blocked), { variant: "info" });
- return false;
- }
- updateEntry(id, { sending: true, error: undefined });
- const request = (async () => {
- let targetId = id;
- try {
- if (entry.pending) {
- const result = await api.forkSession(entry.parentSessionId, entry.title, entry.anchorMessageId);
- const child = result.session;
- targetId = child.id;
- commitForkedSession(child, { activate: false, clearError: true });
- // Replace only the original draft's tab. A close or parent switch
- // during the host call must never reopen a panel in another context.
- set((state) => {
- const current = state.sideChats[id];
- if (!current) return {};
- const oldTabId = sideChatWorkPanelTab(id).id;
- const tab = sideChatWorkPanelTab(child.id);
- const replaceTabs = (tabs: AppState["workPanelTabs"]) =>
- tabs.map((item) => item.id === oldTabId ? tab : item);
- return {
- sideChats: registerSideChat(removeSideChat(state.sideChats, id), {
- ...current, sessionId: child.id, title: child.title, pending: false,
- }),
- sideChatTranscripts: {
- ...withoutRecordKey(state.sideChatTranscripts, id),
- [child.id]: forkedSessionMessages(child),
- },
- workPanelTabs: replaceTabs(state.workPanelTabs),
- activeWorkPanelTabId: state.activeWorkPanelTabId === oldTabId ? tab.id : state.activeWorkPanelTabId,
- workPanelContexts: Object.fromEntries(Object.entries(state.workPanelContexts).map(([key, context]) => [key, {
- ...context,
- tabs: replaceTabs(context.tabs),
- activeTabId: context.activeTabId === oldTabId ? tab.id : context.activeTabId,
- }])),
- };
- });
- }
- // Forking may await auth/host work. Check the returned child's live
- // availability, including when its panel was closed during creation.
- const blocked = sideChatSendBlockReason(
- { ...entry, sessionId: targetId, pending: false },
- get().sessions,
- get().runningSessions,
- );
- if (blocked) {
- get().showToast(i18n.t(blocked), { variant: "info" });
- return false;
- }
- const accepted = await get().sendPrompt(text, { text, fileReferences: [] }, targetId);
- if (accepted && get().sideChats[targetId]?.draft === entry.draft) {
- updateEntry(targetId, { draft: "" });
- }
- return accepted;
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- updateEntry(targetId, { error: message });
- set({ error: message, errorCode: (error as { code?: string })?.code ?? null });
- return false;
- } finally {
- updateEntry(targetId, { sending: false });
- }
- })();
- sends.set(id, request);
- try {
- return await request;
- } finally {
- sends.delete(id);
- }
- },
- closeSideChat: (sessionId) => {
- if (!sessionId) return;
- const tabId = sideChatWorkPanelTab(sessionId).id;
- if (get().workPanelTabs.some((tab) => tab.id === tabId)) {
- get().closeWorkPanelTab(tabId);
- }
- set((state) => {
- const sideChats = removeSideChat(state.sideChats, sessionId);
- if (sideChats === state.sideChats) return {};
- // The durable child session stays in the sidebar and in search; only the
- // renderer's panel projection and its tab go away.
- const workPanelContexts = Object.fromEntries(
- Object.entries(state.workPanelContexts).map(([id, context]) => {
- if (!context.tabs.some((tab) => tab.id === tabId)) return [id, context];
- const tabs = context.tabs.filter((tab) => tab.id !== tabId);
- return [
- id,
- {
- ...context,
- tabs,
- activeTabId:
- context.activeTabId === tabId
- ? tabs.at(-1)?.id ?? null
- : context.activeTabId,
- },
- ];
- }),
- );
- return {
- sideChats,
- sideChatTranscripts: withoutRecordKey(
- state.sideChatTranscripts,
- sessionId,
- ),
- workPanelContexts,
- };
- });
- },
-
- addSideChatReplyToMain: (sessionId) => {
- const entry = get().sideChats[sessionId];
- if (!entry || entry.pending) return;
- const messages = get().sideChatTranscripts[sessionId] ?? [];
- const answer = [...messages]
- .reverse()
- .find(
- (message) =>
- message.role === "assistant" && Boolean((message.content || "").trim()),
- );
- if (!answer) return;
- get().quoteMessageIntoComposer({ title: entry.title, text: answer.content });
- },
-
- abortSession: async (sessionId) => {
- if (!sessionId) return;
- try {
- await api.abort(sessionId);
- } finally {
- set((state) => ({
- isRunning:
- state.activeSessionId === sessionId ? false : state.isRunning,
- runningSessions: { ...state.runningSessions, [sessionId]: false },
- }));
- }
- },
-
- };
-}
diff --git a/apps/desktop/src/stores/slices/work-panel-slice.ts b/apps/desktop/src/stores/slices/work-panel-slice.ts
index 5c9eb15e6..2fc5ae354 100644
--- a/apps/desktop/src/stores/slices/work-panel-slice.ts
+++ b/apps/desktop/src/stores/slices/work-panel-slice.ts
@@ -1,4 +1,3 @@
-import { removeSideChat, sideChatTabSessionId } from "../../lib/side-chat";
import { api } from "../../lib/api";
import {
activateWorkPanelTabState,
@@ -295,7 +294,6 @@ export function createWorkPanelSlice({
set((state) => {
const sessionId = state.activeSessionId;
if (!sessionId) return {};
- const closedTab = state.workPanelTabs.find((tab) => tab.id === tabId);
const next = closeWorkPanelTabState(
{
tabs: state.workPanelTabs,
@@ -304,17 +302,6 @@ export function createWorkPanelSlice({
tabId,
);
const activeTab = next.tabs.find((tab) => tab.id === next.activeTabId);
- // A side chat's tab is its only panel surface, so closing the tab releases
- // the side chat. Its child session is durable and stays in the sidebar,
- // where it can be opened as an ordinary conversation (D-LOCAL-message-quotes).
- const releasedSessionId = sideChatTabSessionId(closedTab);
- const sideChats = releasedSessionId
- ? removeSideChat(state.sideChats, releasedSessionId)
- : state.sideChats;
- const sideChatTranscripts =
- releasedSessionId && sideChats !== state.sideChats
- ? Object.fromEntries(Object.entries(state.sideChatTranscripts).filter(([id]) => id !== releasedSessionId))
- : state.sideChatTranscripts;
const fileRequest =
activeTab?.kind === "file" && activeTab.resource
? {
@@ -332,8 +319,6 @@ export function createWorkPanelSlice({
fileRequest,
};
return {
- sideChats,
- sideChatTranscripts,
workPanelTabs: next.tabs,
activeWorkPanelTabId: next.activeTabId,
workPanelOpen: state.workPanelOpen,
diff --git a/apps/desktop/src/styles/globals.css b/apps/desktop/src/styles/globals.css
index 3f48850c4..f26469bf1 100644
--- a/apps/desktop/src/styles/globals.css
+++ b/apps/desktop/src/styles/globals.css
@@ -29,7 +29,6 @@
@import "./project-create-dialog.css";
@import "./sessions.css";
@import "./work-panel.css";
-@import "./side-chat.css";
@import "./providers.css";
@import "./model-config.css";
@import "./chat-links.css";
diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.css
index 486059111..3372ee4e1 100644
--- a/apps/desktop/src/styles/messages.css
+++ b/apps/desktop/src/styles/messages.css
@@ -953,311 +953,6 @@
opacity: 1;
}
-/*
- * Floating quote affordance for a selection (ADR message-quotes-and-side-chats). Fixed, and in the
- * body-portaled popover layer: it is read while the passage underneath stays
- * visible, so it must clear the docked composer without pushing the passage
- * around (D-layer table in 04-ux/07-ui-design-system.md §9).
- */
-/*
- * Floating selection overlay (D-LOCAL-selection-overlay): one pill above the selection, with the
- * action row's text buttons separated by hairlines and the icon action last —
- * the ChatGPT overlay contract. Fixed, and in the body-portaled popover layer,
- * so it clears the docked composer without pushing the passage around.
- */
-.selection-quote {
- position: fixed;
- z-index: 60; /* z-command-palette: body-portaled popovers */
- display: inline-flex;
- align-items: center;
- padding: 3px;
- border: 1px solid var(--ds-border-default);
- border-radius: var(--radius-full);
- background: var(--ds-bg-elevated-opaque);
- color: var(--ds-text-primary);
- font-size: var(--text-xs-plus);
- line-height: var(--leading-compact);
- box-shadow: var(--ds-shadow-dialog);
- animation: selection-quote-in var(--motion-duration-fast) var(--motion-ease-out);
-}
-
-.selection-quote-action {
- display: inline-flex;
- align-items: center;
- gap: 5px;
- min-height: 22px;
- padding: 3px 9px;
- border: 0;
- border-radius: var(--radius-full);
- background: transparent;
- color: inherit;
- font: inherit;
- white-space: nowrap;
- cursor: pointer;
- transition: background var(--motion-duration-fast) var(--motion-ease-out);
-}
-
-.selection-quote-action:hover:not(:disabled) {
- background: var(--ds-bg-hover);
-}
-
-.selection-quote-action:active:not(:disabled) {
- transform: scale(0.96);
-}
-
-.selection-quote-action:disabled {
- color: var(--ds-text-faint);
- cursor: default;
-}
-
-.selection-quote-action.icon {
- padding: 3px 7px;
-}
-
-.selection-quote-action:focus-visible {
- outline: 2px solid var(--ds-accent);
- outline-offset: 1px;
-}
-
-/* Hairline between actions, sized by the row rather than by the text. */
-.selection-quote-sep {
- align-self: stretch;
- width: 1px;
- background: var(--ds-border-default);
-}
-
-/*
- * Inline numbered reference to one response annotation (D-LOCAL-response-annotations).
- *
- * The reference implementation renders this as a small accent-colored link with
- * a dashed underline on hover, not as a chip: it sits inside a sentence, so it
- * must not disturb the line it annotates. The excerpt (and any comment) is the
- * tooltip, and the marker never joins a selection or a copy.
- */
-.response-annotation-marker {
- display: inline;
- margin: 0;
- padding: 0 1px;
- border: 0;
- background: transparent;
- color: var(--ds-info);
- font: inherit;
- font-size: var(--text-2xs);
- line-height: inherit;
- vertical-align: super;
- text-underline-offset: 2px;
- cursor: pointer;
- user-select: none;
-}
-
-.response-annotation-marker:hover,
-.response-annotation-marker:focus-visible {
- text-decoration: underline dashed;
- text-decoration-thickness: 0.5px;
-}
-
-.response-annotation-marker:focus-visible {
- outline: 2px solid var(--ds-accent);
- outline-offset: 1px;
-}
-
-/* A collapsible index floats above the composer; it reserves no transcript space. */
-.response-annotation-float {
- position: absolute;
- right: 16px;
- bottom: calc(var(--composer-dock-height, 150px) + 12px);
- z-index: 35;
- max-width: calc(100% - 32px);
- border: 1px solid var(--ds-border-subtle);
- border-radius: var(--radius-lg);
- background: var(--ds-bg-elevated-opaque);
- box-shadow: var(--ds-shadow-dialog);
- color: var(--ds-text-primary);
- font-size: var(--text-sm);
-}
-.response-annotation-float-head,
-.response-annotation-float-toggle,
-.response-annotation-locate {
- display: flex;
- align-items: center;
- gap: 6px;
-}
-.response-annotation-float-head { padding: 6px 8px; }
-.response-annotation-float-toggle,
-.response-annotation-locate {
- border: 0;
- padding: 2px;
- background: transparent;
- color: inherit;
- text-align: start;
- cursor: pointer;
-}
-.response-annotation-float-toggle { flex: 1; }
-.response-annotation-float-list {
- list-style: none;
- width: 300px;
- max-width: 100%;
- max-height: min(280px, calc(100vh - var(--composer-dock-height, 150px) - 100px));
- margin: 0;
- padding: 4px;
- overflow: auto;
-}
-.response-annotation-locate { flex: 1; min-width: 0; align-items: flex-start; }
-.response-annotation-number,
-.response-annotation-source-badge {
- display: inline-grid;
- place-items: center;
- flex: 0 0 auto;
- min-width: 22px;
- height: 22px;
- border: 1px solid var(--ds-accent);
- border-radius: var(--radius-full);
- color: var(--ds-accent);
- background: var(--ds-bg-elevated-opaque);
- font-size: var(--text-xs);
- font-variant-numeric: tabular-nums;
-}
-.response-annotation-source-layer { pointer-events: none; user-select: none; }
-.response-annotation-source-badge {
- position: fixed;
- z-index: 34;
- pointer-events: auto;
- user-select: none;
- cursor: pointer;
-}
-.response-annotation-source-badge.active,
-.composer-annotation-item.active { background: var(--ds-bg-hover); }
-.response-annotation-highlight {
- position: fixed;
- z-index: 33;
- pointer-events: none;
- background: color-mix(in srgb, var(--ds-accent) 18%, transparent);
-}
-
-.composer-annotation-item {
- display: flex;
- flex-direction: column;
- gap: 4px;
- padding: 6px 7px;
- border-radius: var(--radius-sm);
-}
-
-.composer-annotation-item:hover {
- background: var(--ds-bg-hover);
-}
-
-.composer-annotation-item-head {
- display: flex;
- align-items: flex-start;
- gap: 6px;
-}
-
-.composer-annotation-item-text {
- display: -webkit-box;
- flex: 1 1 auto;
- min-width: 0;
- overflow: hidden;
- overflow-wrap: anywhere;
- color: var(--ds-text-primary);
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-}
-
-.composer-annotation-item-comment {
- margin: 0 0 0 18px;
- color: var(--ds-text-secondary);
- white-space: pre-wrap;
- overflow-wrap: anywhere;
-}
-
-.composer-annotation-item-action {
- display: inline-flex;
- flex: 0 0 auto;
- align-items: center;
- justify-content: center;
- width: 20px;
- height: 20px;
- border: 0;
- border-radius: var(--radius-sm);
- background: transparent;
- color: var(--ds-text-muted);
- cursor: pointer;
-}
-
-.composer-annotation-item-action:hover:not(:disabled) {
- background: var(--ds-bg-hover);
- color: var(--ds-text-primary);
-}
-
-/*
- * The annotation comment editor (D-LOCAL-response-annotations): the excerpt snapshot above the
- * multiline comment field, with Save and Cancel in the shared dialog rhythm.
- */
-.response-annotation-dialog {
- width: min(100%, 440px);
-}
-
-.response-annotation-quote-label {
- display: block;
- margin-bottom: 7px;
- color: var(--ds-text-secondary);
- font-size: var(--text-sm);
-}
-
-.response-annotation-quote-text {
- margin: 0 0 12px;
- max-height: 120px;
- overflow-y: auto;
- padding: 1px 0 1px 10px;
- border-left: 2px solid var(--ds-border-default);
- color: var(--ds-text-secondary);
- font-size: var(--text-sm);
- line-height: var(--leading-body);
- white-space: pre-wrap;
- overflow-wrap: anywhere;
-}
-
-.response-annotation-comment-input {
- min-height: 76px;
- max-height: 200px;
- resize: vertical;
- font-size: var(--text-sm);
- line-height: var(--leading-body);
-}
-
-.composer-annotation-clear {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 18px;
- height: 18px;
- border: 0;
- border-radius: var(--radius-full);
- background: transparent;
- color: inherit;
- cursor: pointer;
-}
-
-.composer-annotation-clear:hover {
- background: var(--ds-bg-hover);
- color: var(--ds-text-primary);
-}
-
-@keyframes selection-quote-in {
- from {
- opacity: 0;
- }
- to {
- opacity: 1;
- }
-}
-
-@media (prefers-reduced-motion: reduce) {
- .selection-quote {
- animation: none;
- }
-}
-
.icon-btn:active:not(:disabled),
.title-nav-btn:active:not(:disabled),
.nav-item:active:not(:disabled),
diff --git a/apps/desktop/src/styles/side-chat.css b/apps/desktop/src/styles/side-chat.css
deleted file mode 100644
index 834a7e609..000000000
--- a/apps/desktop/src/styles/side-chat.css
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- Side chat: a follow-up conversation docked in the work panel (D-LOCAL-message-quotes).
-
- The panel owns the tab chrome and the width; this partial owns the three rows
- inside it — actions, the child session's transcript, and the compact composer.
- A side chat is a full conversation, so the transcript keeps the chat surface's
- own styles and only its container is sized here.
-*/
-
-.side-chat {
- display: flex;
- flex: 1;
- min-height: 0;
- flex-direction: column;
-}
-
-.side-chat-actions {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- padding: 8px 10px;
- border-bottom: 1px solid var(--ds-border-subtle);
-}
-
-.side-chat-action {
- white-space: nowrap;
-}
-
-/* The transcript keeps its own scroll container; this cell only bounds it. */
-.side-chat-thread {
- position: relative;
- display: flex;
- flex: 1;
- min-height: 0;
- flex-direction: column;
-}
-
-.side-chat-composer {
- display: flex;
- flex-direction: column;
- gap: 6px;
- padding: 8px 10px 10px;
- border-top: 1px solid var(--ds-border-subtle);
- background: var(--ds-bg-secondary);
-}
-
-.side-chat-input {
- width: 100%;
- min-height: 46px;
- max-height: 140px;
- padding: 8px 10px;
- color: var(--ds-text-primary);
- background: var(--ds-bg-primary);
- border: 1px solid var(--ds-border-default);
- border-radius: var(--radius-sm);
- font-size: var(--text-sm);
- line-height: var(--leading-row);
- resize: none;
-}
-
-.side-chat-input::placeholder {
- color: var(--ds-text-muted);
-}
-
-.side-chat-input:focus-visible {
- outline: 2px solid var(--ds-accent);
- outline-offset: -1px;
-}
-
-.side-chat-composer-row {
- display: flex;
- min-height: 24px;
- align-items: center;
- gap: 8px;
-}
-
-.side-chat-hint {
- flex: 1;
- min-width: 0;
- color: var(--ds-text-muted);
- font-size: var(--text-xs);
-}
diff --git a/apps/desktop/test/annotation-only-send.test.mjs b/apps/desktop/test/annotation-only-send.test.mjs
deleted file mode 100644
index 5b6f85fc4..000000000
--- a/apps/desktop/test/annotation-only-send.test.mjs
+++ /dev/null
@@ -1,144 +0,0 @@
-import { readStoreSource, readComposerSource } from "./helpers/source-contracts.mjs";
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import { runInNewContext } from "node:vm";
-import test from "node:test";
-import ts from "typescript";
-import { responseAnnotationPrompt, requestTextWithoutAnnotations } from "../src/lib/response-annotations.ts";
-
-const source = await readComposerSource();
-const ast = ts.createSourceFile("Composer.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-function initializer(name) {
- let result;
- function visit(node) {
- if (ts.isVariableDeclaration(node) && node.name.getText(ast) === name) result = node.initializer.getText(ast);
- ts.forEachChild(node, visit);
- }
- visit(ast);
- assert.ok(result, `${name} must exist in the real composer`);
- return result;
-}
-const submitCode = ts.transpileModule(`const submit = ${initializer("submit")};`, {
- compilerOptions: { target: ts.ScriptTarget.ES2022 },
-}).outputText + "submit();";
-const annotation = { id: "a1", messageId: "m1", text: "selected text", annotation: "explain this", createdAt: 1 };
-
-function harness({ text = "", annotations = [annotation], sendBlocked = false, modelReady = true, accepted = true } = {}) {
- const state = { activeSessionId: "s1", responseAnnotations: { s1: annotations } };
- const sent = [];
- const restored = [];
- const context = {
- value: text, draft: {
- ref: { current: null },
- draftSnapshot: (value) => ({ text: value.trim(), fileReferences: [] }),
- clearDraftForKey() {},
- restoreDraftForKey: (key, value) => restored.push([key, value]),
- }, activeSessionId: "s1", activeFileReferences: [],
- useAppStore: { getState: () => state }, hasAnnotations: annotations.length > 0,
- serializeInlineComposerFileReferences: (value) => value.trim(),
- serializeComposerFileReferences: (value) => value.trim(),
- sendBlocked, pasting: false, modelReady, draftKey: "s1",
- invalidatePromptEnhancement() {}, clearDraftForKey() {},
- showToast() {}, t: (key) => key,
- draftSnapshot: (value) => ({ text: value.trim(), fileReferences: [] }),
- restoreDraftForKey: (key, draft) => restored.push([key, draft]),
- sendPrompt: async (content, draft) => {
- sent.push({ content, draft, wire: responseAnnotationPrompt(content, state.responseAnnotations.s1) });
- if (accepted) state.responseAnnotations.s1 = [];
- return accepted;
- },
- };
- context.steerPrompt = async (content, draft) => { sent.push({ content, draft, steering: true }); return accepted; };
- return { state, sent, restored, context, submit: (steering = false) => runInNewContext(`(async () => { ${submitCode.replace("submit();", `return submit(${steering});`)} })()`, context) };
-}
-
-test("saved annotations enable Send even when the composer text is empty", () => {
- for (const value of ["", " \n"]) {
- assert.equal(runInNewContext(initializer("hasDraftContent"), { value, hasAnnotations: true }), true);
- assert.equal(runInNewContext(initializer("hasDraftContent"), { value, hasAnnotations: false }), false);
- }
- assert.match(source, /runActive && !hasDraftContent/);
- assert.match(source, /disabled=\{\s*!hasDraftContent \|\|\s*sendBlocked/);
-});
-
-test("the real submit handler sends only saved annotations without inventing request text", async () => {
- const view = harness();
- await view.submit();
- assert.equal(view.sent.length, 1);
- assert.equal(view.sent[0].content, "");
- assert.equal(view.sent[0].draft.text, "");
- assert.ok(view.sent[0].wire.includes('"annotation":"explain this"'));
- assert.equal(requestTextWithoutAnnotations(view.sent[0].wire), "");
- assert.equal(view.state.responseAnnotations.s1.length, 0);
- // A second click before React updates must not send an empty prompt.
- await view.submit();
- assert.equal(view.sent.length, 1);
-});
-
-test("empty, blocked, unconfigured and other-session annotations do not bypass send gates", async () => {
- for (const options of [{ annotations: [] }, { sendBlocked: true }, { modelReady: false }]) {
- const view = harness(options);
- await view.submit();
- assert.equal(view.sent.length, 0);
- }
- const other = harness();
- other.state.responseAnnotations = { s2: [annotation] };
- await other.submit();
- assert.equal(other.sent.length, 0);
-});
-
-test("a rejected annotation-only submit retains the annotations", async () => {
- const view = harness({ accepted: false });
- await view.submit();
- assert.equal(view.sent.length, 1);
- assert.equal(view.state.responseAnnotations.s1.length, 1);
- assert.equal(view.restored.length, 1);
-});
-
-test("the real store queues an annotation-only prompt while the session is running", async () => {
- const store = await readStoreSource();
- const storeAst = ts.createSourceFile("app-store.ts", store, ts.ScriptTarget.Latest, true);
- let handler;
- function visit(node) {
- if (ts.isPropertyAssignment(node) && node.name.getText(storeAst) === "sendPrompt") handler = node.initializer.getText(storeAst);
- ts.forEachChild(node, visit);
- }
- visit(storeAst);
- assert.ok(handler);
- const queued = [];
- const state = { activeSessionId: "s1", pendingPlans: {}, runningSessions: { s1: true }, sessions: [], sideChats: {},
- responseAnnotations: { s1: [annotation], s2: [annotation] },
- enqueuePrompt: async (...args) => { queued.push(args); return true; },
- };
- const code = ts.transpileModule(`const send = ${handler};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- const accepted = await runInNewContext(code + 'send("", { text: "", fileReferences: [] });', {
- pendingSubmissions: new Set(), get: () => state, set: (update) => Object.assign(state, update(state)), responseAnnotationPrompt,
- });
- assert.equal(accepted, true);
- assert.equal(queued.length, 1);
- assert.equal(queued[0][2], "s1");
- assert.equal(queued[0][0], responseAnnotationPrompt("", [annotation]));
- assert.equal(state.responseAnnotations.s1, undefined);
- assert.equal(state.responseAnnotations.s2.length, 1);
-});
-
-test("a host-trimmed annotation-only prompt never exposes the wire block in the transcript", () => {
- const wire = responseAnnotationPrompt("", [annotation]);
- assert.equal(requestTextWithoutAnnotations(wire.trim()), "");
- const request = "Explain this heading:\n## My request: extra";
- assert.equal(requestTextWithoutAnnotations(responseAnnotationPrompt(request, [annotation])), request);
-});
-
-
-test("steering is text-only and preserves saved annotations; annotation-only steering does nothing", async () => {
- const empty = harness();
- await empty.submit(true);
- assert.equal(empty.sent.length, 0);
- assert.equal(empty.state.responseAnnotations.s1.length, 1);
- const text = harness({ text: "steer the active turn" });
- await text.submit(true);
- assert.equal(text.sent.length, 1);
- assert.equal(text.sent[0].steering, true);
- assert.equal(text.sent[0].content, "steer the active turn");
- assert.equal(text.state.responseAnnotations.s1.length, 1);
-});
diff --git a/apps/desktop/test/chat-quotes.test.mjs b/apps/desktop/test/chat-quotes.test.mjs
deleted file mode 100644
index 1282a3b4d..000000000
--- a/apps/desktop/test/chat-quotes.test.mjs
+++ /dev/null
@@ -1,69 +0,0 @@
-import { readStoreSource, readTranscriptSource } from "./helpers/source-contracts.mjs";
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import test from "node:test";
-import {
- MAX_QUOTE_CHARS,
- appendQuoteToDraft,
- buildQuoteText,
- quoteExcerpt,
-} from "../src/lib/chat-quotes.ts";
-
-const transcript = await readTranscriptSource();
-const store = await readStoreSource();
-
-test("a quote carries the selected text when there is a selection", () => {
- assert.equal(
- quoteExcerpt("the whole answer", "only this part"),
- "only this part",
- );
- assert.equal(quoteExcerpt("the whole answer", " "), "the whole answer");
- assert.equal(quoteExcerpt("the whole answer"), "the whole answer");
-});
-
-test("a quote normalizes line endings and trims the excerpt", () => {
- assert.equal(quoteExcerpt(" first\r\nsecond \r\n"), "first\nsecond");
-});
-
-test("a long excerpt is cut once and marked with an ellipsis", () => {
- const excerpt = quoteExcerpt("x".repeat(MAX_QUOTE_CHARS + 500));
- assert.equal(excerpt.length, MAX_QUOTE_CHARS + 1);
- assert.ok(excerpt.endsWith("…"));
-});
-
-test("a cut never splits a surrogate pair", () => {
- // The bound lands between the two halves of the astral character, so the
- // excerpt must drop the lone high surrogate instead of emitting it.
- const excerpt = quoteExcerpt(`${"a".repeat(MAX_QUOTE_CHARS - 1)}😀tail`);
- assert.equal(excerpt.length, MAX_QUOTE_CHARS);
- assert.doesNotMatch(excerpt, /[\uD800-\uDBFF]$/);
-});
-
-test("quote text is a blockquote plus its attribution", () => {
- assert.equal(
- buildQuoteText("one\ntwo", "Quoted from Fix the parser"),
- "> one\n> two\n\nQuoted from Fix the parser",
- );
- assert.equal(
- buildQuoteText("one\n\ntwo", "Quoted from Fix the parser"),
- "> one\n>\n> two\n\nQuoted from Fix the parser",
- );
-});
-
-test("quoting appends to a draft instead of replacing it", () => {
- assert.equal(appendQuoteToDraft("", "> quoted"), "> quoted");
- assert.equal(appendQuoteToDraft("do this: ", "> quoted"), "do this:\n\n> quoted");
-});
-
-test("the quote action is wired to the composer draft and never sends", () => {
- assert.match(transcript, /quoteMessageIntoComposer\(\{/);
- assert.match(transcript, /selectionMarkdownWithinRow\(message\.id\)/);
- assert.match(transcript, /selectionMarkdownWithinRow\(entry\.anchorId\)/);
- assert.match(transcript, /t\("chat\.quote"\)/);
- // Quoting only edits a draft: no prompt, session, or transcript write.
- assert.match(store, /quoteMessageIntoComposer: \(\{ title, text, selection \}\)/);
- assert.match(store, /buildQuoteText\(\s*excerpt,/);
- assert.match(store, /i18n\.t\("chat\.quoteSource", \{ title \}\)/);
- assert.match(store, /appendComposerDraftText: \(text\) => \{/);
- assert.match(store, /appendQuoteToDraft\(draft\?\.text \?\? "", text\)/);
-});
diff --git a/apps/desktop/test/composer-send-state.test.mjs b/apps/desktop/test/composer-send-state.test.mjs
index 951b27312..a4bfe505b 100644
--- a/apps/desktop/test/composer-send-state.test.mjs
+++ b/apps/desktop/test/composer-send-state.test.mjs
@@ -290,9 +290,8 @@ test("mode slash prefixes send the trailing prompt and retain failed drafts", ()
assert.match(sendPrompt, /return false;/);
assert.match(
sendPrompt,
- // An annotated send ships the block the model reads, not the bare draft
- // text, so the prompt call carries the composed prompt (D-LOCAL-response-annotations).
- /await api\.prompt\(\{[\s\S]*?sessionId,[\s\S]*?content: outgoing,[\s\S]*?attachments:[\s\S]*?promptAttachmentsFromDraft\(draft\.fileReferences\)[\s\S]*?\}\);[\s\S]*?return true;/,
+ // The prompt call carries the submitted content and attachment mapping.
+ /await api\.prompt\(\{[\s\S]*?sessionId,[\s\S]*?content,[\s\S]*?attachments:[\s\S]*?promptAttachmentsFromDraft\(draft\.fileReferences\)[\s\S]*?\}\);[\s\S]*?return true/,
);
});
diff --git a/apps/desktop/test/native-pi-sessions.test.mjs b/apps/desktop/test/native-pi-sessions.test.mjs
index 45214d647..cd685953a 100644
--- a/apps/desktop/test/native-pi-sessions.test.mjs
+++ b/apps/desktop/test/native-pi-sessions.test.mjs
@@ -337,8 +337,6 @@ test("native terminal events re-key exactly the provisional row they name", asyn
const state = {
activeSessionId: id,
messages: [provisional, otherStream],
- sideChats: { [id]: { sessionId: id, parentSessionId: "native-pi:parent", title: "Side chat", anchorMessageId: "a1" } },
- sideChatTranscripts: { [id]: [provisional, otherStream] },
retainedTranscripts: { [id]: [provisional, otherStream] },
runningSessions: { [id]: true },
isRunning: true,
@@ -357,7 +355,6 @@ test("native terminal events re-key exactly the provisional row they name", asyn
});
for (const rows of [
state.messages,
- state.sideChatTranscripts[id],
state.retainedTranscripts[id],
runtime.sessionTranscriptCache.get(id),
]) {
@@ -404,27 +401,6 @@ test("a generic Desktop completion never touches parallel delegate streams", asy
assert.equal(settled[1].status, "streaming");
});
-test("a durable native user entry reconciles the side-chat projection", () => {
- const id = "native-pi:child";
- const state = {
- activeSessionId: "other-session",
- messages: [],
- sideChats: { [id]: { sessionId: id, parentSessionId: "native-pi:parent", title: "Side chat", anchorMessageId: "a1" } },
- sideChatTranscripts: { [id]: [user("optimistic-1")] },
- retainedTranscripts: {},
- };
- const runtime = {
- liveSessionTranscripts: new Set(),
- sessionTranscriptCache: new Map(),
- cacheSessionTranscript: (key, rows) => runtime.sessionTranscriptCache.set(key, rows),
- };
- const slice = createEventsSlice({ ...stateHarness(state), runtime });
- const event = { type: "user_message_persisted", optimisticMessageId: "optimistic-1", message: user("durable-1") };
- slice.handleAgentEvent({ sessionId: id, ts: 1, event });
- slice.handleAgentEvent({ sessionId: id, ts: 2, event });
- assert.deepEqual(state.sideChatTranscripts[id].map((row) => row.id), ["durable-1"]);
-});
-
const queueSlice = await read("../src/stores/slices/queue-slice.ts");
test("a running native side-chat send fails before the Desktop queue", () => {
@@ -443,109 +419,3 @@ test("the native busy message is localized in every locale", async () => {
assert.match(source, /nativeSessionBusy:/, locale);
}
});
-
-test("an off-active side-chat send failure is visible in the child and never in main", async () => {
- const { useAppStore } = await import("../src/stores/app-store.ts");
- const { api } = await import("../src/lib/api.ts");
- const id = "native-pi:child";
- useAppStore.setState({
- activeSessionId: "other-session",
- sessions: [{ id: "other-session", source: "desktop" }],
- messages: [],
- sideChats: {
- [id]: { sessionId: id, parentSessionId: "native-pi:parent", title: "Side chat", anchorMessageId: "a1" },
- },
- sideChatTranscripts: { [id]: [] },
- runningSessions: {},
- queuedPrompts: {},
- latestTurnResults: {},
- sessionOutcomes: {},
- toasts: [],
- });
- const originalPrompt = api.prompt;
- api.prompt = async () => {
- throw Object.assign(new Error("Native Pi provider is unavailable"), {
- code: "NATIVE_PI_PROVIDER_UNAVAILABLE",
- });
- };
- try {
- const accepted = await useAppStore
- .getState()
- .sendPrompt("child draft", { text: "child draft", fileReferences: [] }, id);
- assert.equal(accepted, false);
- const rows = useAppStore.getState().sideChatTranscripts[id];
- assert.equal(rows.filter((row) => row.status === "error").length, 1);
- assert.match(rows.at(-1).error.message, /provider is unavailable/);
- assert.equal(useAppStore.getState().messages.length, 0, "no error row in the main transcript");
- assert.equal(
- useAppStore.getState().toasts.some((toast) => /provider is unavailable/.test(toast.message)),
- true,
- "the failure is visible as a toast",
- );
- } finally {
- api.prompt = originalPrompt;
- }
-});
-
-test("a native error before the first assistant surfaces in the off-active side chat", () => {
- const id = "native-pi:child";
- const toasts = [];
- const state = {
- activeSessionId: "other-session",
- messages: [],
- sideChats: {
- [id]: { sessionId: id, parentSessionId: "native-pi:parent", title: "Side chat", anchorMessageId: "a1" },
- },
- sideChatTranscripts: { [id]: [] },
- runningSessions: { [id]: true },
- isRunning: false,
- agentStatuses: {},
- latestTurnResults: {},
- sessionOutcomes: {},
- pendingPermissions: {},
- pendingAsks: {},
- showToast: (message, options) => toasts.push({ message, options }),
- };
- const runtime = {
- liveSessionTranscripts: new Set(),
- sessionTranscriptCache: new Map(),
- submittedComposerDrafts: new Map(),
- cacheSessionTranscript: (key, rows) => runtime.sessionTranscriptCache.set(key, rows),
- projectSideChatEvent: () => {},
- cacheBackgroundTranscriptEvent: () => {},
- };
- const withoutRecordKey = (record, key) => {
- if (!(key in record)) return record;
- const next = { ...record };
- delete next[key];
- return next;
- };
- const slice = createEventsSlice({
- ...stateHarness(state),
- runtime,
- withoutRecordKey,
- flushPendingSessionConfiguration: async () => {},
- assistantErrorMessage: (error) => ({
- id: "native-error-row",
- role: "assistant",
- content: "",
- createdAt: "2026-09-14T00:00:00Z",
- status: "error",
- isError: true,
- error,
- }),
- });
- slice.handleAgentEvent({
- sessionId: id,
- ts: 9,
- event: {
- type: "error",
- error: { code: "NATIVE_PI_RUNTIME_ERROR", message: "native runtime failed", retriable: false },
- },
- });
- assert.equal(state.sideChatTranscripts[id].length, 1);
- assert.equal(state.sideChatTranscripts[id][0].status, "error");
- assert.equal(toasts.length, 1);
- assert.match(toasts[0].message, /native runtime failed/);
- assert.equal(state.messages.length, 0);
-});
diff --git a/apps/desktop/test/plan-mode-source-contract.test.mjs b/apps/desktop/test/plan-mode-source-contract.test.mjs
index b0b2cd782..32a2fac3d 100644
--- a/apps/desktop/test/plan-mode-source-contract.test.mjs
+++ b/apps/desktop/test/plan-mode-source-contract.test.mjs
@@ -106,8 +106,8 @@ test("reject or interruption returns editable planning without changing durable
queueSource.slice(queueSource.indexOf("sendPrompt: async"));
assert.match(sendPromptBlock, /get\(\)\.pendingPlans\[sessionId\]\?\.status === "pending"/);
assert.match(sendPromptBlock, /await api\.prompt\(\{/);
- // The send ships the composed prompt so annotations travel with it (D-LOCAL-response-annotations).
- assert.match(sendPromptBlock, /sessionId,\s*content: outgoing,/);
+ // The send ships the submitted content through the prompt call.
+ assert.match(sendPromptBlock, /sessionId,\s*content,/);
assert.match(
sendPromptBlock,
/attachments: draft[\s\S]*promptAttachmentsFromDraft\(draft\.fileReferences\)/,
diff --git a/apps/desktop/test/response-annotation-anchor.test.mjs b/apps/desktop/test/response-annotation-anchor.test.mjs
deleted file mode 100644
index a938fe706..000000000
--- a/apps/desktop/test/response-annotation-anchor.test.mjs
+++ /dev/null
@@ -1,74 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { register } from "node:module";
-register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
-const { resolveAnnotationOffsets, placeAnnotationBadges, captureAnnotationAnchor, annotationRange } = await import("../src/lib/response-annotation-anchor.ts");
-import { annotationEditorFor, applyAnnotationComment, responseAnnotationPrompt } from "../src/lib/response-annotations.ts";
-
-test("the second occurrence stays the second occurrence; ambiguous stale anchors never guess", () => {
- const anchor = { start: 4, end: 7, exact: "foo" };
- assert.deepEqual(resolveAnnotationOffsets("foo foo", anchor), { start: 4, end: 7 });
- assert.equal(resolveAnnotationOffsets("x foo foo", anchor), null);
- assert.deepEqual(resolveAnnotationOffsets("prefix foo", anchor), { start: 7, end: 10 });
- assert.equal(resolveAnnotationOffsets("gone", anchor), null);
-});
-
-test("capture and resolution use offsets across split text nodes and never modify their text", () => {
- const nodes = ["hello ", "world", " world"].map((data) => ({
- data, textContent: data, length: data.length,
- parentElement: { closest: (selector) => selector === ".prose-chat" ? {} : null },
- }));
- const range = {
- startContainer: nodes[1], startOffset: 1, endContainer: nodes[2], endOffset: 4,
- cloneRange() { return this; }, intersectsNode: (node) => node !== nodes[0],
- };
- const recovered = {};
- const row = { contains: () => true, ownerDocument: {
- createTreeWalker: () => { let i = 0; return { nextNode: () => nodes[i++] }; },
- createRange: () => ({
- setStart: (node, offset) => { recovered.start = [nodes.indexOf(node), offset]; },
- setEnd: (node, offset) => { recovered.end = [nodes.indexOf(node), offset]; },
- }),
- } };
- const anchor = captureAnnotationAnchor(row, range);
- assert.deepEqual(anchor, { start: 7, end: 15, exact: "orld wor" });
- assert.ok(annotationRange(row, anchor));
- assert.deepEqual(recovered, { start: [1, 1], end: [2, 4] });
- assert.equal(nodes.map((node) => node.data).join(""), "hello world world");
-});
-
-test("same words at distinct positions or in different answers keep separate numbers", () => {
- const anchor = { start: 0, end: 3, exact: "foo" };
- const first = annotationEditorFor([], { sessionId: "s", messageId: "m1", text: "foo", anchor });
- let annotations = applyAnnotationComment([], first, "first", "a1", 1);
- const second = annotationEditorFor(annotations, { sessionId: "s", messageId: "m1", text: "foo", anchor: { ...anchor, start: 4, end: 7 } });
- assert.equal(second.annotationId, null);
- annotations = applyAnnotationComment(annotations, second, "second", "a2", 2);
- const third = annotationEditorFor(annotations, { sessionId: "s", messageId: "m2", text: "foo", anchor });
- annotations = applyAnnotationComment(annotations, third, "third", "a3", 3);
- assert.deepEqual(annotations.map((item) => item.id), ["a1", "a2", "a3"]);
- assert.equal(annotationEditorFor(annotations, { sessionId: "s", messageId: "m1", text: "foo", anchor }).annotationId, "a1");
- const prompt = responseAnnotationPrompt("review", annotations);
- assert.ok(prompt.includes('"annotation":"second"'));
- assert.ok(!prompt.includes('"anchor"'));
- assert.ok(!prompt.includes('"exact"'));
-});
-
-test("whole-answer and selected-answer entry points reopen one annotation in either order", () => {
- const input = { sessionId: "s", messageId: "m1", text: "whole answer" };
- const anchor = { start: 0, end: 12, exact: "whole answer" };
- for (const firstAnchor of [undefined, anchor]) {
- const first = annotationEditorFor([], { ...input, anchor: firstAnchor });
- const annotations = applyAnnotationComment([], first, "keep", "a1", 1);
- const secondInput = { ...input, anchor: firstAnchor ? undefined : anchor };
- assert.equal(annotationEditorFor(annotations, secondInput).annotationId, "a1");
- // A stale create request must not insert the same answer under a new number.
- assert.equal(applyAnnotationComment(annotations,
- { ...secondInput, annotationId: null, comment: "" }, "new", "a2", 2), null);
- }
-});
-
-test("badges sharing a line stack visibly and never escape the transcript band", () => {
- const placed = placeAnnotationBadges([{ top: 12, id: "2" }, { top: 10, id: "1" }, { top: 12, id: "3" }], 0, 75);
- assert.deepEqual(placed, [{ top: 10, id: "1" }, { top: 35, id: "2" }]);
-});
diff --git a/apps/desktop/test/response-annotation-dialog.test.mjs b/apps/desktop/test/response-annotation-dialog.test.mjs
deleted file mode 100644
index a02d3519d..000000000
--- a/apps/desktop/test/response-annotation-dialog.test.mjs
+++ /dev/null
@@ -1,198 +0,0 @@
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import test from "node:test";
-import { runInNewContext } from "node:vm";
-import ts from "typescript";
-
-// Exercise the real component's handlers/effects without Electron or a DOM
-// dependency. This is not a browser layout or end-to-end test.
-const source = await readFile(new URL("../src/components/ResponseAnnotationDialog.tsx", import.meta.url), "utf8");
-const compiled = ts.transpileModule(source, {
- compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX },
-}).outputText;
-
-function mount({ previousFocus } = {}) {
- const effects = [];
- const hooks = [];
- const listeners = new Map();
- let cursor = 0;
- let tree;
- let closed = 0;
- let saved;
- const document = { body: { style: { overflow: "auto" }, isConnected: true, focus() {} } };
- document.activeElement = previousFocus ?? document.body;
- if (previousFocus) previousFocus.focus = () => { document.activeElement = previousFocus; };
- const composer = { focus() { document.activeElement = composer; } };
- document.querySelector = (selector) => selector.includes('[contenteditable="true"]') ? composer : null;
- const state = {
- activeSessionId: "s1",
- responseAnnotationEditor: { sessionId: "s1", messageId: "m1", text: "$x^2$", annotationId: null, comment: "" },
- saveResponseAnnotationEditor: (value) => { saved = value; },
- closeResponseAnnotationEditor: () => { closed++; },
- };
- const jsx = (type, props) => ({ type, props });
- const modules = {
- react: {
- useEffect: (effect) => { effects.push(effect); },
- useRef: () => hooks[cursor++] ??= { current: null },
- useState: (initial) => {
- const index = cursor++;
- if (!(index in hooks)) hooks[index] = initial;
- return [hooks[index], (value) => { hooks[index] = value; }];
- },
- },
- "react/jsx-runtime": { jsx, jsxs: jsx },
- "react-dom": { createPortal: (node) => node },
- "react-i18next": { useTranslation: () => ({ t: (key) => key }) },
- "../stores/app-store": { useAppStore: (select) => select(state) },
- "./ui": { Button: "button", TooltipButton: "button" },
- "./icons": { IconChat: "svg", IconClose: "svg" },
- };
- const exports = {};
- runInNewContext(compiled, {
- exports, require: (id) => { assert.ok(id in modules, id); return modules[id]; },
- document,
- window: {
- addEventListener: (name, handler, capture) => {
- if (name === "keydown") assert.equal(capture, true, "modal keyboard handling must precede app shortcuts");
- listeners.set(name, handler);
- },
- removeEventListener: (name) => listeners.delete(name),
- },
- requestAnimationFrame: (callback) => { effects.push(callback); return 1; },
- cancelAnimationFrame() {},
- });
- function nodes(node = tree) {
- if (!node || typeof node !== "object") return [];
- return [node, ...[node.props?.children].flat(Infinity).flatMap((child) => nodes(child ?? null))];
- }
- function render() {
- cursor = 0;
- const component = exports.ResponseAnnotationDialog();
- tree = component.type(component.props);
- const all = nodes();
- for (const node of all) {
- node.isConnected = true;
- node.focus = () => { document.activeElement = node; };
- node.setSelectionRange = () => {};
- node.value = node.props.value ?? "";
- node.querySelectorAll = () => all.filter((item) => item.type === "button" || item.type === "textarea");
- if (node.props.ref) node.props.ref.current = node;
- }
- }
- render();
- const cleanups = [];
- for (const effect of effects.splice(0)) {
- const cleanup = effect();
- if (cleanup) cleanups.push(cleanup);
- }
- for (const frame of effects.splice(0)) frame();
- return {
- nodes, render, document, composer,
- renderHost: () => exports.ResponseAnnotationDialog(),
- state,
- get closed() { return closed; },
- get saved() { return saved; },
- key: (overrides) => {
- const event = { key: "Escape", preventDefault() {}, stopImmediatePropagation() { this.stopped = true; }, ...overrides };
- listeners.get("keydown")(event);
- return event;
- },
- unmount: () => { for (const cleanup of cleanups) cleanup(); },
- };
-}
-
-test("the mounted editor shows the excerpt, focuses the comment and saves typed content", () => {
- const view = mount();
- assert.ok(view.nodes().some((node) => node.props.role === "dialog"));
- assert.equal(view.nodes().find((node) => node.type === "blockquote").props.children, "$x^2$");
- const input = view.nodes().find((node) => node.type === "textarea");
- assert.equal(view.document.activeElement, input);
- input.props.onChange({ target: { value: "请解释这一步" } });
- view.render();
- view.nodes().find((node) => node.type === "form").props.onSubmit({ preventDefault() {} });
- assert.equal(view.saved, "请解释这一步");
- assert.equal(view.closed, 0);
-});
-
-test("Enter saves the live comment, Shift+Enter inserts a newline, and IME Enter never saves", () => {
- const view = mount();
- const input = view.nodes().find((node) => node.type === "textarea");
- const key = (overrides = {}) => {
- const event = {
- key: "Enter", nativeEvent: {}, currentTarget: { value: "最新评价\n第二行" },
- preventDefault() { this.prevented = true; },
- stopPropagation() { this.stopped = true; }, ...overrides,
- };
- input.props.onKeyDown?.(event);
- return event;
- };
- for (const event of [
- { shiftKey: true }, { nativeEvent: { isComposing: true } },
- { nativeEvent: { keyCode: 229 } }, { key: "a" },
- ]) {
- assert.equal(key(event).prevented, undefined, "typing and IME keep their native behavior");
- assert.equal(view.saved, undefined);
- }
- assert.equal(key({ repeat: true }).prevented, true);
- assert.equal(view.saved, undefined, "holding Enter must not repeat a save");
- const enter = key();
- assert.equal(view.saved, "最新评价\n第二行", "save the DOM value, not stale React state");
- assert.equal(enter.prevented, true);
- assert.equal(enter.stopped, true);
- assert.equal(view.closed, 0);
-});
-
-test("IME Escape keeps the editor open; ordinary Escape is owned by the dialog", () => {
- const view = mount();
- view.key({ isComposing: true });
- view.key({ keyCode: 229 });
- assert.equal(view.closed, 0, "IME candidate cancellation must not discard the comment");
- const event = view.key({});
- assert.equal(view.closed, 1);
- assert.equal(event.stopped, true, "Escape must not also reach application shortcuts");
-});
-
-test("only a press starting on the backdrop dismisses, not a selection drag ending there", () => {
- const view = mount();
- const backdrop = view.nodes()[0];
- backdrop.props.onClick?.({ target: backdrop, currentTarget: backdrop });
- assert.equal(view.closed, 0, "a synthesized click after dragging text must not discard it");
- backdrop.props.onPointerDown({ target: {}, currentTarget: backdrop });
- assert.equal(view.closed, 0);
- backdrop.props.onPointerDown({ target: backdrop, currentTarget: backdrop, preventDefault() {} });
- assert.equal(view.closed, 1);
-});
-
-test("Tab stays inside the dialog and Cancel never saves", () => {
- const view = mount();
- const controls = view.nodes().filter((node) => node.type === "button" || node.type === "textarea");
- controls.at(-1).focus();
- view.key({ key: "Tab" });
- assert.equal(view.document.activeElement, controls[0]);
- view.key({ key: "Tab", shiftKey: true });
- assert.equal(view.document.activeElement, controls.at(-1));
- controls.find((node) => node.props.children === "common.cancel").props.onClick();
- assert.equal(view.closed, 1);
- assert.equal(view.saved, undefined);
-});
-
-test("the host renders nothing after switching to another session", () => {
- const view = mount();
- view.state.activeSessionId = "s2";
- assert.equal(view.renderHost(), null);
-});
-
-test("closing an editor opened from the list restores its connected trigger", () => {
- const trigger = { isConnected: true };
- const view = mount({ previousFocus: trigger });
- view.unmount();
- assert.equal(view.document.activeElement, trigger);
-});
-
-test("closing from the selection overlay restores focus to the rich composer", () => {
- const view = mount();
- view.unmount();
- assert.equal(view.document.activeElement, view.composer);
- assert.equal(view.document.body.style.overflow, "auto");
-});
diff --git a/apps/desktop/test/response-annotation-editor.test.mjs b/apps/desktop/test/response-annotation-editor.test.mjs
deleted file mode 100644
index 86d5c3296..000000000
--- a/apps/desktop/test/response-annotation-editor.test.mjs
+++ /dev/null
@@ -1,235 +0,0 @@
-import { readStoreModule, readTranscriptSource } from "./helpers/source-contracts.mjs";
-/**
- * The comment editor's flow (ADR response-annotations / D-LOCAL-response-annotations), driven through the same pure
- * transitions the store calls: opening from an excerpt, saving the comment into
- * the annotation, re-editing an already attached excerpt, and dropping a save
- * whose annotation was already sent or removed.
- */
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import test from "node:test";
-import {
- annotationEditorFor,
- applyAnnotationComment,
- responseAnnotationPrompt,
-} from "../src/lib/response-annotations.ts";
-
-const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
-const store = await readStoreModule("slices/annotation-slice.ts");
-const composer = await read("../src/components/ResponseAnnotationOverlay.tsx");
-const overlay = await read("../src/components/SelectionQuoteButton.tsx");
-const transcript = await readTranscriptSource();
-const dialog = await read("../src/components/ResponseAnnotationDialog.tsx");
-
-test("Add to chat opens the comment editor instead of attaching the excerpt", () => {
- assert.deepEqual(
- annotationEditorFor([], {
- sessionId: "s1",
- messageId: "m1",
- text: " a quoted pass ",
- }),
- {
- sessionId: "s1",
- messageId: "m1",
- text: "a quoted pass",
- annotationId: null,
- comment: "",
- },
- );
- // A blank excerpt has nothing to quote and opens nothing.
- assert.equal(
- annotationEditorFor([], { sessionId: "s1", messageId: "m1", text: " " }),
- null,
- );
-});
-
-test("saving attaches the excerpt with its comment in attachment order", () => {
- const first = annotationEditorFor([], {
- sessionId: "s1",
- messageId: "m1",
- text: "first pass",
- });
- const one = applyAnnotationComment([], first, " explain this ", "a1", 5);
- assert.deepEqual(one, [
- {
- id: "a1",
- messageId: "m1",
- text: "first pass",
- annotation: "explain this",
- createdAt: 5,
- },
- ]);
- // A save with an empty comment still attaches: Add to chat works without one.
- const second = annotationEditorFor(one, {
- sessionId: "s1",
- messageId: "m2",
- text: "second pass",
- });
- const two = applyAnnotationComment(one, second, "", "a2", 9);
- assert.deepEqual(
- two.map((annotation) => [annotation.id, annotation.annotation]),
- [
- ["a1", "explain this"],
- ["a2", ""],
- ],
- );
-});
-
-test("an already attached excerpt reopens for editing and is never doubled", () => {
- const existing = [
- {
- id: "a1",
- messageId: "m1",
- text: "the pass",
- annotation: "old",
- createdAt: 1,
- },
- ];
- const reopened = annotationEditorFor(existing, {
- sessionId: "s1",
- messageId: "m1",
- text: "the pass",
- });
- assert.deepEqual(reopened, {
- sessionId: "s1",
- messageId: "m1",
- text: "the pass",
- annotationId: "a1",
- comment: "old",
- });
- const updated = applyAnnotationComment(existing, reopened, "new", "a2", 9);
- assert.deepEqual(updated, [
- {
- id: "a1",
- messageId: "m1",
- text: "the pass",
- annotation: "new",
- createdAt: 1,
- },
- ]);
- // Re-saving the same comment changes nothing, and a duplicate attachment of
- // the same excerpt is refused.
- assert.equal(applyAnnotationComment(existing, reopened, "old", "a3", 9), null);
- assert.equal(
- applyAnnotationComment(
- existing,
- {
- sessionId: "s1",
- messageId: "m1",
- text: "the pass",
- annotationId: null,
- comment: "",
- },
- "again",
- "a4",
- 9,
- ),
- null,
- );
-});
-
-test("a saved and edited comment reaches the model as structured data", () => {
- const editor = annotationEditorFor([], {
- sessionId: "s1", messageId: "m1", text: "$x^2$",
- });
- const saved = applyAnnotationComment([], editor, "initial", "a1", 1);
- const reopened = annotationEditorFor(saved, {
- sessionId: "s1", messageId: "m1", text: "$x^2$", annotationId: "a1",
- });
- const updated = applyAnnotationComment(saved, reopened, '解释 "x"\n再举例', "a2", 2);
- const prompt = responseAnnotationPrompt("please review", updated);
- const payload = JSON.parse(prompt.split("<response-annotations>\n")[1].split("\n</response-annotations>")[0]);
- assert.deepEqual(payload, [{
- text: "$x^2$", annotation: '解释 "x"\n再举例', source: { messageId: "m1" },
- }]);
- assert.ok(prompt.endsWith("## My request:\nplease review"));
-});
-
-test("a stale editor never restores a sent or removed annotation", () => {
- // The explicit edit target no longer exists: no editor opens for it, and no
- // save recreates it.
- assert.equal(
- annotationEditorFor([], {
- sessionId: "s1",
- messageId: "m1",
- text: "gone",
- annotationId: "a1",
- }),
- null,
- );
- assert.equal(
- applyAnnotationComment(
- [],
- {
- sessionId: "s1",
- messageId: "m1",
- text: "gone",
- annotationId: "a1",
- comment: "",
- },
- "resurrect me",
- "a9",
- 1,
- ),
- null,
- );
-});
-
-test("the editor belongs to the session it was opened in", () => {
- const editor = annotationEditorFor([], {
- sessionId: "s1",
- messageId: "m1",
- text: "the pass",
- });
- assert.equal(editor.sessionId, "s1");
- // A session switch must not keep editing another session's annotations.
- assert.match(dialog, /editor\.sessionId === activeSessionId/);
- assert.match(dialog, /editor\.sessionId !== activeSessionId/);
-});
-
-test("the quote surfaces open the editor and never attach directly", () => {
- assert.match(
- overlay,
- /openResponseAnnotationEditor\(\{\s*messageId: target\.rowAnchorId,\s*text: target\.markdown,\s*anchor: selectionAnnotationAnchorWithinRow\(target\.rowAnchorId\),\s*\}\)/,
- );
- assert.match(
- transcript,
- /openResponseAnnotationEditor\(\{\s*messageId: entry\.anchorId,\s*text: selection \|\| content,\s*anchor: selectionAnnotationAnchorWithinRow\(entry\.anchorId\),\s*\}\)/,
- );
- assert.doesNotMatch(overlay, /addResponseAnnotation/);
- assert.doesNotMatch(transcript, /addResponseAnnotation/);
-});
-
-test("the store saves the editor through the annotation transition", () => {
- assert.match(store, /responseAnnotationEditor: annotationEditorFor\(current, \{/);
- assert.match(
- store,
- /const next = applyAnnotationComment\(\s*current,\s*editor,\s*comment,\s*crypto\.randomUUID\(\),\s*\);/,
- );
- // A no-op save closes the editor without resurrecting the annotation.
- assert.match(store, /if \(!next\) return \{ responseAnnotationEditor: null \};/);
- assert.match(store, /\[editor\.sessionId\]: next/);
-});
-
-test("the floating index lists each annotation with edit and remove actions", () => {
- assert.match(composer, /data-testid="composer-annotation-menu"/);
- assert.match(composer, /data-testid="composer-annotation-item"/);
- assert.match(
- composer,
- /edit\(\{\s*messageId: annotation\.messageId,\s*text: annotation\.text,\s*annotationId: annotation\.id\s*\}\)/,
- );
- assert.match(composer, /remove\(annotation\.id\)/);
- assert.match(composer, /aria-expanded=\{expanded\}/);
- assert.ok(composer.includes('ariaLabel={`${t("chat.annotationEdit")} ${index + 1}`}'));
- assert.ok(composer.includes('ariaLabel={`${t("chat.annotationRemove")} ${index + 1}`}'));
-});
-
-test("the comment editor is accessible, saves on submit, and never sends", () => {
- assert.match(dialog, /role="dialog"/);
- assert.match(dialog, /aria-modal="true"/);
- assert.match(dialog, /event\.key === "Escape"/);
- assert.match(dialog, /input\.focus\(\)/);
- assert.match(dialog, /t\("chat\.annotationCommentPlaceholder"\)/);
- assert.match(dialog, /onSave\(comment\)/);
- assert.doesNotMatch(dialog, /sendPrompt|api\.prompt/);
-});
diff --git a/apps/desktop/test/response-annotation-overlay.test.mjs b/apps/desktop/test/response-annotation-overlay.test.mjs
deleted file mode 100644
index 4ff599bac..000000000
--- a/apps/desktop/test/response-annotation-overlay.test.mjs
+++ /dev/null
@@ -1,128 +0,0 @@
-import { readTranscriptSource } from "./helpers/source-contracts.mjs";
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import { runInNewContext } from "node:vm";
-import test from "node:test";
-import ts from "typescript";
-import { intersectSelectionQuoteRect } from "../src/lib/selection-quote.ts";
-
-const source = await readFile(new URL("../src/components/ResponseAnnotationOverlay.tsx", import.meta.url), "utf8");
-const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX } }).outputText;
-
-test("the floating index collapses, expands, navigates by id and edits/removes the same numbered item", () => {
- const annotations = [{ id: "a1", messageId: "m1", text: "first", annotation: "comment" },
- { id: "a2", messageId: "m2", text: "second", annotation: "" }];
- let edited, removed, navigated, cleared = false;
- const state = { responseAnnotations: { s: annotations },
- openResponseAnnotationEditor: (value) => { edited = value; },
- removeResponseAnnotation: (id) => { removed = id; },
- clearResponseAnnotations: () => { cleared = true; },
- };
- const hooks = [];
- let cursor = 0;
- const jsx = (type, props) => ({ type, props });
- const modules = {
- react: { useEffect() {}, useLayoutEffect() {}, useRef: () => ({ current: null }),
- useState: (initial) => { const i = cursor++; if (!(i in hooks)) hooks[i] = initial; return [hooks[i], (value) => { hooks[i] = typeof value === "function" ? value(hooks[i]) : value; }]; },
- },
- "react/jsx-runtime": { jsx, jsxs: jsx, Fragment: "fragment" },
- "react-dom": { createPortal: (node) => node },
- "react-i18next": { useTranslation: () => ({ t: (key) => key }) },
- "../stores/app-store": { useAppStore: (select) => select(state) },
- "../lib/response-annotation-anchor": {}, "../lib/selection-quote": {},
- "./icons": {}, "./ui": { TooltipButton: "button" },
- };
- const exports = {};
- runInNewContext(compiled, { exports, require: (id) => { assert.ok(id in modules, id); return modules[id]; }, document: { body: {} } });
- let tree;
- const render = () => { cursor = 0; tree = exports.ResponseAnnotationOverlay({ sessionId: "s", scrollRef: { current: null }, onNavigate: (annotation) => { navigated = annotation; } }); };
- const nodes = (node) => !node || typeof node !== "object" ? [] : [node, ...[node.props?.children].flat(Infinity).flatMap(nodes)];
- const find = (predicate) => nodes(tree).find(predicate);
- render();
- assert.ok(find((node) => node.type === "aside"));
- assert.equal(find((node) => node.props["aria-expanded"] !== undefined).props["aria-expanded"], true);
- find((node) => node.props["aria-expanded"] !== undefined).props.onClick();
- render();
- assert.ok(!find((node) => node.type === "ol"));
- find((node) => node.props["aria-expanded"] !== undefined).props.onClick();
- render();
- find((node) => node.props["aria-label"] === "chat.annotationLocate 2").props.onClick();
- assert.equal(navigated, annotations[1]);
- find((node) => node.props.ariaLabel === "chat.annotationEdit 2").props.onClick();
- assert.equal(edited.annotationId, "a2");
- find((node) => node.props.ariaLabel === "chat.annotationRemove 1").props.onClick();
- assert.equal(removed, "a1");
- find((node) => node.props.ariaLabel === "chat.clearAnnotations").props.onClick();
- assert.equal(cleared, true);
- // Geometry belongs to the previous layout until the layout effect runs. A
- // removal must not dereference an old array index or display the wrong number.
- hooks[2] = { badges: [
- { id: "a1", index: 1, top: 10, left: 10, exact: true },
- { id: "a2", index: 2, top: 40, left: 10, exact: true },
- ], highlights: [] };
- state.responseAnnotations.s = [annotations[1]];
- render();
- const badges = nodes(tree).filter((node) => node.props.className?.startsWith("response-annotation-source-badge"));
- assert.equal(badges.length, 1);
- assert.equal(badges[0].props.children, 1);
- assert.equal(badges[0].props.title, "second");
- state.responseAnnotations.s = [];
- render();
- assert.equal(tree, null);
-});
-
-test("all saved resolved ranges stay highlighted without selecting an item or expanding the index", () => {
- const ast = ts.createSourceFile("overlay.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
- let effect;
- function visit(node) {
- if (ts.isCallExpression(node) && node.expression.getText(ast) === "useLayoutEffect") {
- effect = node.arguments[0].getText(ast);
- }
- ts.forEachChild(node, visit);
- }
- visit(ast);
- assert.ok(effect, "exercise the real layout effect, not a copied implementation");
- const executable = ts.transpileModule(`(${effect})();`, {
- compilerOptions: { target: ts.ScriptTarget.ES2022 },
- }).outputText;
- const rect = (top) => ({ top, bottom: top + 20, left: 20, right: 80, width: 60, height: 20 });
- const saved = [{ id: "a1", messageId: "m1", anchor: [rect(20)] },
- { id: "a2", messageId: "m2", anchor: [rect(60)] },
- { id: "stale", messageId: "m3" }];
- for (const [annotations, activeId, expanded, expected] of [
- [saved, null, true, [20, 60]],
- [saved, "a1", true, [20, 60]],
- [saved, "a2", false, [20, 60]],
- [saved.slice(1), null, false, [60]],
- [[], null, false, []],
- ]) {
- let geometry;
- const root = { addEventListener() {}, removeEventListener() {} };
- class Observer { observe() {} disconnect() {} }
- const cleanup = runInNewContext(executable, {
- annotations, activeId, expanded, scrollRef: { current: root },
- setGeometry: (value) => { geometry = value; },
- document: { querySelector: () => null },
- window: { innerWidth: 100, innerHeight: 100, addEventListener() {}, removeEventListener() {} },
- COMPOSER_DOCK_SELECTOR: "dock",
- selectionQuoteBounds: () => ({ top: 0, bottom: 100, left: 0, right: 100 }),
- annotationRow: () => ({ getBoundingClientRect: () => rect(0) }),
- annotationRange: (_, anchor) => anchor ? { getClientRects: () => anchor } : null,
- intersectSelectionQuoteRect,
- placeAnnotationBadges: (badges) => badges,
- ResizeObserver: Observer, MutationObserver: Observer, cancelAnimationFrame() {},
- });
- assert.deepEqual(Array.from(geometry.highlights, (item) => item.top), expected);
- cleanup?.();
- }
-});
-
-test("only the visible writable pane owns badges and navigation releases follow mode", async () => {
- const transcript = await readTranscriptSource();
- assert.match(transcript, /!transcriptReadOnly && paneVisible && !veilCovering && sessionId/);
- assert.match(transcript, /const navigateAnnotation[\s\S]*?pinnedRef\.current = false/);
- assert.match(transcript, /requestAnimationFrame\(\(\) => setWindowSize\(\(size\) =>\s*Math\.min\(Math\.max\(size, allHistoryEntries\.length - index\),\s*growTranscriptWindow\(size, allHistoryEntries\.length\)\)\)/);
- assert.match(transcript, /annotationPagesRef\.current\.has\(messages\.length\)/);
- assert.match(source, /root\.addEventListener\("scroll", schedule/);
- assert.match(source, /mutation\.disconnect\(\)/);
-});
diff --git a/apps/desktop/test/response-annotations.test.mjs b/apps/desktop/test/response-annotations.test.mjs
deleted file mode 100644
index 212056bb6..000000000
--- a/apps/desktop/test/response-annotations.test.mjs
+++ /dev/null
@@ -1,192 +0,0 @@
-import { readStoreSource, readTranscriptSource } from "./helpers/source-contracts.mjs";
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import test from "node:test";
-import {
- ANNOTATION_BLOCK_CLOSE,
- ANNOTATION_BLOCK_HEADING,
- ANNOTATION_BLOCK_OPEN,
- ANNOTATION_INSTRUCTION,
- ANNOTATION_REQUEST_HEADING,
- MAX_ANNOTATION_CHARS,
- annotationExcerpt,
- annotationMarkerToken,
- requestTextWithoutAnnotations,
- responseAnnotation,
- responseAnnotationPrompt,
- splitAnnotationMarkerTokens,
-} from "../src/lib/response-annotations.ts";
-
-const store = await readStoreSource();
-const transcript = await readTranscriptSource();
-const markdown = await readFile(
- new URL("../src/components/Markdown.tsx", import.meta.url),
- "utf8",
-);
-const composer = await readFile(
- new URL("../src/components/ResponseAnnotationOverlay.tsx", import.meta.url),
- "utf8",
-);
-const overlay = await readFile(
- new URL("../src/components/SelectionQuoteButton.tsx", import.meta.url),
- "utf8",
-);
-const selectionQuote = await readFile(
- new URL("../src/lib/selection-quote.ts", import.meta.url),
- "utf8",
-);
-const styles = await readFile(
- new URL("../src/styles/messages.css", import.meta.url),
- "utf8",
-);
-
-const annotation = (overrides = {}) => ({
- id: "a1",
- messageId: "m1",
- text: "the quoted pass",
- annotation: "",
- createdAt: 0,
- ...overrides,
-});
-
-test("the prompt carries the annotation block the model reads", () => {
- const prompt = responseAnnotationPrompt("explain this", [
- annotation(),
- annotation({ id: "a2", messageId: "m2", text: "and this" }),
- ]);
- assert.equal(
- prompt,
- [
- ANNOTATION_BLOCK_HEADING,
- ANNOTATION_INSTRUCTION,
- ANNOTATION_BLOCK_OPEN,
- '[{"text":"the quoted pass","annotation":"","source":{"messageId":"m1"}},{"text":"and this","annotation":"","source":{"messageId":"m2"}}]',
- ANNOTATION_BLOCK_CLOSE,
- "",
- ANNOTATION_REQUEST_HEADING,
- "explain this",
- ].join("\n"),
- );
- // A session without annotations sends the draft untouched.
- assert.equal(responseAnnotationPrompt("explain this", []), "explain this");
-});
-
-test("a stored annotated prompt reduces back to the user's request", () => {
- const prompt = responseAnnotationPrompt("explain this", [annotation()]);
- assert.equal(requestTextWithoutAnnotations(prompt), "explain this");
- // A plain prompt is left alone, and a prompt that merely looks similar is not
- // truncated.
- assert.equal(requestTextWithoutAnnotations("explain this"), "explain this");
- assert.equal(
- requestTextWithoutAnnotations(`## My request:\nplain`),
- `## My request:\nplain`,
- );
-});
-
-test("an excerpt is capped without cutting a surrogate pair", () => {
- assert.equal(annotationExcerpt(" keep me "), "keep me");
- assert.equal(annotationExcerpt("a\r\nb"), "a\nb");
- const capped = annotationExcerpt("x".repeat(MAX_ANNOTATION_CHARS + 5));
- assert.equal(capped.length, MAX_ANNOTATION_CHARS + 1);
- assert.ok(capped.endsWith("…"));
- const surrogate = annotationExcerpt(`${"a".repeat(MAX_ANNOTATION_CHARS - 1)}😀tail`);
- assert.doesNotMatch(surrogate, /[\uD800-\uDBFF]$/);
-});
-
-test("a new annotation keeps its excerpt and starts without a comment", () => {
- const created = responseAnnotation({
- id: "a9",
- messageId: "m7",
- text: " a pass ",
- createdAt: 5,
- });
- assert.deepEqual(created, {
- id: "a9",
- messageId: "m7",
- text: "a pass",
- annotation: "",
- createdAt: 5,
- });
-});
-
-test("a marker token round-trips through the split the renderer uses", () => {
- const source = `before${annotationMarkerToken(2)}after`;
- assert.deepEqual(splitAnnotationMarkerTokens(source), [
- { kind: "text", value: "before" },
- { kind: "marker", index: 2 },
- { kind: "text", value: "after" },
- ]);
- // Text without tokens stays one segment, so the pipeline can skip the work.
- assert.deepEqual(splitAnnotationMarkerTokens("plain"), [
- { kind: "text", value: "plain" },
- ]);
-});
-
-test("the markdown pass turns marker tokens into numbered references", () => {
- assert.match(markdown, /remarkAnnotationMarkers/);
- assert.match(markdown, /const staticRemarkPlugins = \[remarkGfm, remarkMath, remarkAnnotationMarkers\]/);
- assert.match(markdown, /url: annotationMarkerHref\(segment\.index\)/);
- assert.match(markdown, /if \(annotationIndex !== null\) \{\s*return <AnnotationMarker index=\{annotationIndex\} \/>;\s*\}/);
- // Without a whitelisted scheme the sanitizer drops the href and the raw
- // directive would render as link text.
- assert.match(markdown, /href: \[\.\.\.\(defaultSchema\.protocols\?\.href \?\? \[\]\), ANNOTATION_MARKER_SCHEME\.replace\(\/:\$\/, ""\)\]/);
- // The reference renders a numbered reference with the excerpt (and comment)
- // as its tooltip.
- assert.match(markdown, /\[index - 1\]/);
- assert.match(markdown, /t\("chat\.annotationSelectedText"\)/);
- assert.match(markdown, /t\("chat\.annotationComment"\)/);
- assert.match(markdown, /t\("chat\.annotationMarker", \{ index \}\)/);
- assert.match(markdown, /className="response-annotation-marker"/);
- assert.match(markdown, /aria-label=\{t\("chat\.annotationMarker"/);
-});
-
-test("the answer body is never decorated with markers of our own", () => {
- // The reference marks an annotation only where the model cites it: the
- // transcript renders the answer source as it arrived.
- assert.match(transcript, /<Markdown source=\{part\.message\.content\} \/>/);
- assert.doesNotMatch(transcript, /sourceWithMarkers|annotationMarkers\(/);
- assert.doesNotMatch(transcript, /sourceWithAnnotationMarkers/);
-});
-
-test("a marker never joins a quote, a copy, or a selection", () => {
- assert.match(selectionQuote, /"\.response-annotation-marker",/);
- assert.match(styles, /\.response-annotation-marker \{[\s\S]*?user-select: none/);
- assert.match(styles, /\.response-annotation-marker:hover,[\s\S]*?text-decoration: underline dashed/);
-});
-
-test("annotations attach to assistant turns, not to the draft", () => {
- // The row has to say what it is before a selection can be routed.
- assert.match(transcript, /data-row-role="assistant"/);
- assert.match(transcript, /data-row-role=\{isSessionMessage \? undefined : "user"\}/);
- // Attaching goes through the comment editor state the store owns (D-LOCAL-response-annotations).
- assert.match(
- store,
- /openResponseAnnotationEditor: \(\{ messageId, text, annotationId, anchor \}\) => \{/,
- );
- assert.match(store, /annotationEditorFor\(current, \{/);
-});
-
-test("sending carries the annotations and consumes them", () => {
- assert.match(store, /const outgoing = responseAnnotationPrompt\(content, annotations\);/);
- assert.match(store, /content: outgoing,/);
- assert.match(store, /isDefaultSessionTitle\(current\?\.title\)[\s\S]*?promptFallbackSessionTitle\(\s*content,/);
- assert.match(store, /consumeAnnotations\(\)/);
- // Queued prompts are sends too.
- assert.match(store, /await get\(\)\.enqueuePrompt\(outgoing, draft, sessionId\);/);
-});
-
-test("the floating annotation index exposes count, locate, edit and clear", () => {
- assert.match(composer, /data-testid="annotation-float"/);
- assert.match(composer, /t\("chat\.annotationChip", \{ count: annotations\.length \}\)/);
- assert.match(composer, /onClick=\{clear\}/);
- assert.match(composer, /onNavigate\(annotation\)/);
-});
-
-test("the overlay annotates a response and quotes anything else", () => {
- assert.match(overlay, /if \(target\.annotatable\) \{/);
- assert.match(
- overlay,
- /openResponseAnnotationEditor\(\{\s*messageId: target\.rowAnchorId,\s*text: target\.markdown,\s*anchor: selectionAnnotationAnchorWithinRow\(target\.rowAnchorId\),\s*\}\);/,
- );
- assert.match(overlay, /quoteMessageIntoComposer\(\{ title, text: target\.markdown \}\)/);
-});
diff --git a/apps/desktop/test/selection-quote.test.mjs b/apps/desktop/test/selection-quote.test.mjs
deleted file mode 100644
index 0140a7f9d..000000000
--- a/apps/desktop/test/selection-quote.test.mjs
+++ /dev/null
@@ -1,218 +0,0 @@
-import { readTranscriptSource, readComposerSource } from "./helpers/source-contracts.mjs";
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import test from "node:test";
-import {
- SELECTION_QUOTE_GAP,
- SELECTION_QUOTE_MARGIN,
- codeFenceFor,
- intersectSelectionQuoteRect,
- normalizeSelectionMarkdown,
- placeSelectionQuote,
-} from "../src/lib/selection-quote.ts";
-
-const source = await readFile(
- new URL("../src/lib/selection-quote.ts", import.meta.url),
- "utf8",
-);
-const overlay = await readFile(
- new URL("../src/components/SelectionQuoteButton.tsx", import.meta.url),
- "utf8",
-);
-const transcript = await readTranscriptSource();
-const composer = await readComposerSource();
-const styles = await readFile(
- new URL("../src/styles/messages.css", import.meta.url),
- "utf8",
-);
-
-const rect = (left, top, width, height) => ({
- left,
- top,
- right: left + width,
- bottom: top + height,
- width,
- height,
-});
-
-test("a fence outgrows the backticks inside the quoted snippet", () => {
- assert.equal(codeFenceFor("plain"), "```");
- assert.equal(codeFenceFor("a ``` fence"), "````");
- assert.equal(codeFenceFor("inline", 1), "`");
- assert.equal(codeFenceFor("a `b` c", 1), "``");
-});
-
-test("rendered whitespace collapses back to source-like text", () => {
- assert.equal(normalizeSelectionMarkdown(" a\r\n b \r\n"), "a\n b");
- assert.equal(normalizeSelectionMarkdown("a\u00a0b"), "a b");
- assert.equal(normalizeSelectionMarkdown("a\n\n\n\nb"), "a\n\nb");
- assert.equal(normalizeSelectionMarkdown("\n \n"), "");
-});
-
-test("a selection scrolled half out of its container anchors to what is visible", () => {
- const bounds = { left: 0, top: 100, right: 400, bottom: 300 };
- assert.deepEqual(intersectSelectionQuoteRect(rect(50, 120, 100, 20), bounds), {
- left: 50,
- top: 120,
- right: 150,
- bottom: 140,
- width: 100,
- height: 20,
- });
- // Partially scrolled out: only the visible strip is left.
- assert.deepEqual(intersectSelectionQuoteRect(rect(50, 80, 100, 40), bounds), {
- left: 50,
- top: 100,
- right: 150,
- bottom: 120,
- width: 100,
- height: 20,
- });
- assert.equal(intersectSelectionQuoteRect(rect(50, 40, 100, 20), bounds), null);
-});
-
-test("the overlay floats above the selection, centered on it", () => {
- const placement = placeSelectionQuote({
- anchor: rect(100, 200, 120, 20),
- size: { width: 200, height: 30 },
- bounds: { left: 0, top: 0, right: 800, bottom: 600 },
- });
- assert.deepEqual(placement, {
- top: 200 - SELECTION_QUOTE_GAP - 30,
- left: 160 - 100,
- maxWidth: 800 - SELECTION_QUOTE_MARGIN * 2,
- });
-});
-
-test("the overlay is clamped into its bounds on both axes", () => {
- const bounds = { left: 40, top: 100, right: 360, bottom: 300 };
- // A selection against the right edge slides left instead of escaping.
- const atRight = placeSelectionQuote({
- anchor: rect(340, 200, 20, 20),
- size: { width: 200, height: 30 },
- bounds,
- });
- assert.equal(atRight.left, bounds.right - SELECTION_QUOTE_MARGIN - 200);
- assert.ok(atRight.left + 200 <= bounds.right - SELECTION_QUOTE_MARGIN);
-
- // A selection at the top of the bounds keeps the pill inside them.
- const atTop = placeSelectionQuote({
- anchor: rect(100, 102, 100, 20),
- size: { width: 200, height: 30 },
- bounds,
- });
- assert.equal(atTop.top, bounds.top + SELECTION_QUOTE_MARGIN);
-
- // Bounds narrower than the pill cap its width instead of overflowing.
- const narrow = placeSelectionQuote({
- anchor: rect(40, 200, 20, 20),
- size: { width: 200, height: 30 },
- bounds: { left: 0, top: 0, right: 150, bottom: 300 },
- });
- assert.equal(narrow.maxWidth, 150 - SELECTION_QUOTE_MARGIN * 2);
- assert.equal(narrow.left, SELECTION_QUOTE_MARGIN);
-});
-
-test("the bounds are the scroll container, capped above the docked composer", () => {
- // The composer floats over the transcript, so the scroller's own bottom is not
- // the visible bottom (D-LOCAL-selection-overlay).
- assert.match(source, /export const COMPOSER_DOCK_SELECTOR = '\[data-composer-dock="docked"\]'/);
- assert.match(source, /bottomBoundaryTop/);
- assert.match(composer, /data-composer-dock=\{variant\}/);
- // Every clipping ancestor counts, as in the reference overlay.
- assert.match(source, /new Set\(\["auto", "clip", "hidden", "overlay", "scroll"\]\)/);
- assert.match(source, /style\?\.overflowY/);
- assert.match(source, /node = node\.parentElement/);
-});
-
-test("the pill only owns a selection that lives in one row of one transcript", () => {
- assert.match(source, /startRow !== quotableRowFor\(live\.endContainer\)/);
- assert.match(source, /if \(!scrollRoot\.contains\(startRow\)\) return null/);
- // A drag that leaves the row is clamped back to it instead of quoting the
- // next row.
- assert.match(source, /clamped\.compareBoundaryPoints\(Range\.START_TO_START, contents\) < 0/);
- assert.match(source, /clamped\.compareBoundaryPoints\(Range\.END_TO_END, contents\) > 0/);
-});
-
-test("a formula quotes as TeX instead of two duplicated renderings", () => {
- // KaTeX's source lives in the MathML annotation; the visual tree is a copy.
- assert.match(source, /annotation\[encoding="application\/x-tex"\]/);
- assert.match(
- source,
- /replaceWithText\(katex, isDisplay \? `\\n\$\$\\n\$\{tex\}\\n\$\$\\n` : `\$\$\{tex\}\$`, doc\)/,
- );
- assert.match(source, /closest\("\.katex-display"\)/);
- // A partial selection is expanded to the whole formula before cloning.
- assert.match(source, /setStartBefore\(start\)/);
- assert.match(source, /wrapper\.append\(expandRangeToWholeKatex\(range\)\.cloneContents\(\)\)/);
-});
-
-test("a quoted table keeps one line per row and a fence keeps its language", () => {
- assert.match(source, /querySelectorAll\(":scope > th, :scope > td"\)/);
- assert.match(source, /\.join\(" \| "\)/);
- assert.match(source, /querySelectorAll\("\.code-block"\)/);
- assert.match(source, /querySelector\("\.code-block-lang"\)/);
- assert.match(source, /querySelector\("pre code"\)/);
-});
-
-test("quote chrome is dropped but file-reference chips keep their text", () => {
- assert.match(source, /\.message-actions/);
- assert.match(source, /button\.replaceWith\(\.\.\.Array\.from\(button\.childNodes\)\)/);
- assert.doesNotMatch(source, /querySelectorAll\("button"\)\)\s*\{\s*node\.remove/);
-});
-
-test("formulas and code are reduced before chrome is dropped", () => {
- const order = [
- "replaceKatex(wrapper, ownerDocument)",
- "replaceCodeBlocks(wrapper, ownerDocument)",
- "replaceInlineCode(wrapper, ownerDocument)",
- "removeChrome(wrapper)",
- "replaceTables(wrapper, ownerDocument)",
- ].map((step) => source.indexOf(step));
- assert.ok(order.every((index) => index > -1), "every reduction step is present");
- assert.deepEqual(order, [...order].sort((a, b) => a - b), "steps run in order");
-});
-
-test("the overlay follows the selection instead of disappearing on scroll", () => {
- assert.match(overlay, /document\.addEventListener\("selectionchange", schedule\)/);
- assert.match(overlay, /window\.addEventListener\("scroll", onScroll, \{ capture: true, passive: true \}\)/);
- assert.match(overlay, /if \(!row \|\| !\(node instanceof Node\) \|\| !node\.contains\(row\)\) return/);
- for (const event of ["dblclick", "keyup", "pointerup", "pointercancel", "resize"]) {
- assert.match(overlay, new RegExp(`addEventListener\\("${event}"`), event);
- }
- assert.match(overlay, /requestAnimationFrame\(sync\)/);
- // Pressing anywhere else is a new gesture: the pill waits for it to settle.
- assert.match(overlay, /pressedRef\.current = true/);
- assert.match(overlay, /if \(pressedRef\.current\) return/);
- assert.match(overlay, /onPointerDown=\{\(event\) => event\.preventDefault\(\)\}/);
-});
-
-test("the overlay offers add to chat, ask in side chat, and copy", () => {
- assert.match(overlay, /quoteMessageIntoComposer\(\{ title, text: target\.markdown \}\)/);
- assert.match(overlay, /t\("chat\.addToChat"\)/);
- assert.match(overlay, /t\("chat\.askInSideChat"\)/);
- assert.match(overlay, /t\("chat\.copy"\)/);
- assert.match(overlay, /await openSideChat\(target\.rowAnchorId, target\.markdown\)/);
- assert.doesNotMatch(overlay, /sendPrompt\(/);
- // The action consumes the selection, as in the reference overlay.
- assert.match(overlay, /window\.getSelection\(\)\?\.removeAllRanges\(\)/);
- // And it never sends to the conversation being read.
- assert.doesNotMatch(overlay, /activeSessionId \?\s*await sendPrompt|sendPrompt\(target\.markdown, \{[^}]*\}\);/);
-});
-
-test("the transcript mounts the overlay and skips read-only projections", () => {
- assert.match(
- transcript,
- /transcriptReadOnly \|\| !paneVisible \? null : \(\s*<SelectionQuoteButton scrollRef=\{scrollRef\} title=\{sessionTitle\} \/>/,
- );
- // One recovery path: the row actions quote through the same serializer.
- assert.match(transcript, /selectionMarkdownWithinRow\(message\.id\)/);
- assert.match(transcript, /selectionMarkdownWithinRow\(entry\.anchorId\)/);
- assert.doesNotMatch(transcript, /selection\.toString\(\)/);
-});
-
-test("the pill is one rounded action row with hairline separators", () => {
- assert.match(styles, /\.selection-quote \{[\s\S]*?border-radius: var\(--radius-full\)/);
- assert.match(styles, /\.selection-quote-sep \{/);
- assert.match(styles, /\.selection-quote-action:disabled/);
-});
diff --git a/apps/desktop/test/session-message-presentation.test.mjs b/apps/desktop/test/session-message-presentation.test.mjs
index 819f41bbd..812928f6e 100644
--- a/apps/desktop/test/session-message-presentation.test.mjs
+++ b/apps/desktop/test/session-message-presentation.test.mjs
@@ -5,7 +5,6 @@ import * as React from "react";
import * as jsxRuntime from "react/jsx-runtime";
import { renderToStaticMarkup } from "react-dom/server";
import ts from "typescript";
-import { requestTextWithoutAnnotations } from "../src/lib/response-annotations.ts";
const t = (key, values) => values?.name ? `${key}: ${values.name}` : key;
const store = {
@@ -44,9 +43,6 @@ function loadComponent(name, extras = {}) {
"../../../components/icons": new Proxy({}, { get: () => Icon }),
"../../../components/ui": { TooltipButton },
"./shared": shared,
- "./context": { TranscriptReadOnlyContext: React.createContext(false), useActiveSessionTitle: () => "Title" },
- "../../../lib/selection-quote": { selectionMarkdownWithinRow: () => "" },
- "../../../lib/response-annotations": { requestTextWithoutAnnotations },
...extras,
};
const module = { exports: {} };
diff --git a/apps/desktop/test/side-chat-draft.test.mjs b/apps/desktop/test/side-chat-draft.test.mjs
deleted file mode 100644
index 7070e5703..000000000
--- a/apps/desktop/test/side-chat-draft.test.mjs
+++ /dev/null
@@ -1,176 +0,0 @@
-import assert from 'node:assert/strict';
-import test from 'node:test';
-import { register } from 'node:module';
-register(new URL('./helpers/ts-import-hooks.mjs', import.meta.url));
-const { createSideChatSlice } = await import('../src/stores/slices/side-chat-slice.ts');
-const { api } = await import('../src/lib/api.ts');
-
-function fixture() {
- const state = {
- activeSessionId: 'parent', sessions: [{ id: 'parent', title: 'Main' }],
- messages: [{ id: 'a1', role: 'assistant', content: 'Anchor' }],
- toasts: [],
- showToast(message) { state.toasts.push(message); },
- runningSessions: {}, sideChats: {}, sideChatTranscripts: {},
- workPanelTabs: [], activeWorkPanelTabId: null, workPanelContexts: {},
- openWorkPanelTabForSession(parent, tab) {
- assert.equal(parent, 'parent');
- state.workPanelTabs = [tab]; state.activeWorkPanelTabId = tab.id;
- },
- closeWorkPanelTab(id) { state.workPanelTabs = state.workPanelTabs.filter(t => t.id !== id); },
- sendPrompt: async (...args) => { sends.push(args); return true; },
- };
- const sends = [];
- const forks = [];
- api.forkSession = async (...args) => {
- forks.push(args);
- return { session: { id: 'child', title: 'Side', messages: state.messages } };
- };
- Object.assign(state, createSideChatSlice({
- get: () => state,
- set: update => Object.assign(state, typeof update === 'function' ? update(state) : update),
- commitForkedSession: (child, options) => {
- assert.equal(options.activate, false); state.sessions.push(child);
- },
- withoutRecordKey: (record, key) => Object.fromEntries(Object.entries(record).filter(([id]) => id !== key)),
- }));
- return { state, forks, sends };
-}
-
-test('opening, typing, whitespace sending, and closing never create a session', async () => {
- const { state, forks, sends } = fixture();
- const [id, again] = await Promise.all([state.openSideChat('a1'), state.openSideChat('a1')]);
- assert.equal(id, again);
- state.updateSideChatDraft(id, 'not sent');
- assert.equal(state.sessions.length, 1);
- state.updateSideChatDraft(id, ' ');
- assert.equal(await state.sendSideChatPrompt(id), false);
- state.closeSideChat(id);
- assert.deepEqual(state.sideChats, {});
- assert.deepEqual(forks, []); assert.deepEqual(sends, []);
-});
-
-test('selection prefills a quote without sending or replacing existing text', async () => {
- const { state, forks, sends } = fixture();
- const id = await state.openSideChat('a1', 'selected\ntext');
- assert.equal(state.sideChats[id].draft, '> selected\n> text\n\n');
- state.updateSideChatDraft(id, 'my question');
- await state.openSideChat('a1', 'another quote');
- assert.match(state.sideChats[id].draft, /^my question/);
- assert.deepEqual(forks, []); assert.deepEqual(sends, []);
-});
-
-test('first Send creates exactly one child, including concurrent submissions', async () => {
- const { state, forks, sends } = fixture();
- const id = await state.openSideChat('a1');
- state.updateSideChatDraft(id, 'question');
- const results = await Promise.all([state.sendSideChatPrompt(id), state.sendSideChatPrompt(id)]);
- assert.deepEqual(results, [true, true]);
- assert.equal(forks.length, 1); assert.equal(sends.length, 1);
- assert.deepEqual(forks[0].slice(0, 1), ['parent']); assert.equal(forks[0][2], 'a1');
- assert.equal(sends[0][2], 'child'); assert.equal(state.activeSessionId, 'parent');
- assert.equal(state.sideChats.child.draft, '');
- assert.equal(state.workPanelTabs[0].resource, 'child');
- assert.equal(state.sideChats[id], undefined);
- state.closeSideChat('child');
- assert.equal(state.sessions.length, 2);
-});
-
-test('fork failure preserves draft and allows retry', async () => {
- const { state } = fixture();
- const id = await state.openSideChat('a1');
- state.updateSideChatDraft(id, 'keep me');
- const original = api.forkSession;
- api.forkSession = async () => { throw new Error('fork failed'); };
- assert.equal(await state.sendSideChatPrompt(id), false);
- assert.equal(state.sideChats[id].draft, 'keep me');
- assert.equal(state.sideChats[id].sending, false);
- assert.equal(state.sessions.length, 1);
- api.forkSession = original;
- assert.equal(await state.sendSideChatPrompt(id), true);
-});
-
-test('failed prompt reuses the created child on retry and keeps newer draft text', async () => {
- const { state, forks } = fixture();
- const id = await state.openSideChat('a1');
- state.updateSideChatDraft(id, 'first');
- state.sendPrompt = async () => false;
- assert.equal(await state.sendSideChatPrompt(id), false);
- assert.equal(state.sideChats.child.draft, 'first');
- state.sendPrompt = async () => { state.updateSideChatDraft('child', 'newer'); return true; };
- await state.sendSideChatPrompt('child');
- assert.equal(forks.length, 1);
- assert.equal(state.sideChats.child.draft, 'newer');
-});
-
-test('switching parent during fork updates its retained tab without stealing focus', async () => {
- const { state } = fixture();
- const id = await state.openSideChat('a1');
- state.updateSideChatDraft(id, 'question');
- let finish;
- api.forkSession = () => new Promise(resolve => { finish = resolve; });
- const sending = state.sendSideChatPrompt(id);
- state.workPanelContexts.parent = { tabs: state.workPanelTabs, activeTabId: state.activeWorkPanelTabId };
- state.activeSessionId = 'other'; state.workPanelTabs = []; state.activeWorkPanelTabId = null;
- finish({ session: { id: 'child', title: 'Side', messages: [] } });
- await sending;
- assert.equal(state.activeSessionId, 'other'); assert.deepEqual(state.workPanelTabs, []);
- assert.equal(state.workPanelContexts.parent.tabs[0].resource, 'child');
-});
-
-test('closing during an authorized send never resurrects its panel', async () => {
- const { state } = fixture();
- const id = await state.openSideChat('a1');
- state.updateSideChatDraft(id, 'question');
- let finish;
- api.forkSession = () => new Promise(resolve => { finish = resolve; });
- const sending = state.sendSideChatPrompt(id);
- state.closeSideChat(id);
- finish({ session: { id: 'child', title: 'Side', messages: [] } });
- await sending;
- assert.deepEqual(state.sideChats, {}); assert.deepEqual(state.workPanelTabs, []);
- assert.equal(state.sessions.length, 2);
-});
-
-
-test('a parent that starts replying blocks first Send with feedback and recovers', async () => {
- const { state, forks, sends } = fixture();
- const id = await state.openSideChat('a1');
- state.updateSideChatDraft(id, 'keep question');
- state.runningSessions.parent = true;
- assert.equal(await state.sendSideChatPrompt(id), false);
- assert.equal(forks.length, 0); assert.equal(sends.length, 0);
- assert.equal(state.toasts.length, 1);
- assert.equal(state.sideChats[id].draft, 'keep question');
- state.runningSessions.parent = false;
- assert.equal(await state.sendSideChatPrompt(id), true);
- assert.equal(forks.length, 1);
-});
-
-test('read-only parents never create a child; recovery permits first Send', async () => {
- for (const reason of ['provider-unavailable', 'untrusted', 'externally-changed', 'busy']) {
- const { state, forks, sends } = fixture();
- const id = await state.openSideChat('a1');
- state.updateSideChatDraft(id, 'keep question');
- state.sessions[0].readOnlyReason = reason;
- assert.equal(await state.sendSideChatPrompt(id), false, reason);
- assert.equal(forks.length, 0); assert.equal(sends.length, 0);
- assert.equal(state.toasts.length, 1);
- assert.equal(state.sideChats[id].draft, 'keep question');
- delete state.sessions[0].readOnlyReason;
- assert.equal(await state.sendSideChatPrompt(id), true);
- }
-});
-
-test('a child that becomes unavailable during creation is not prompted and is reused', async () => {
- const { state, sends } = fixture();
- const id = await state.openSideChat('a1');
- state.updateSideChatDraft(id, 'keep question');
- api.forkSession = async () => ({session: {id: 'child', title: 'Side', readOnlyReason: 'provider-unavailable', messages: []}});
- assert.equal(await state.sendSideChatPrompt(id), false);
- assert.equal(sends.length, 0); assert.equal(state.toasts.length, 1);
- assert.equal(state.sideChats.child.draft, 'keep question');
- delete state.sessions.find(s => s.id === 'child').readOnlyReason;
- assert.equal(await state.sendSideChatPrompt('child'), true);
- assert.equal(state.sessions.length, 2);
-});
diff --git a/apps/desktop/test/side-chat.test.mjs b/apps/desktop/test/side-chat.test.mjs
deleted file mode 100644
index aa32ee98f..000000000
--- a/apps/desktop/test/side-chat.test.mjs
+++ /dev/null
@@ -1,201 +0,0 @@
-import { readStoreSource, readTranscriptSource } from "./helpers/source-contracts.mjs";
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import test from "node:test";
-import {
- SIDE_CHAT_TAB_PREFIX,
- isSideChatTab,
- registerSideChat,
- removeSideChat,
- removeSideChatsForSessions,
- sideChatEntry,
- sideChatSessionIds,
- sideChatTabSessionId,
- sideChatsForParent,
- sideChatWorkPanelTab,
-} from "../src/lib/side-chat.ts";
-import { isKnownWorkPanelTab } from "../src/lib/work-panel-tabs.ts";
-
-const store = await readStoreSource();
-const panel = await readFile(
- new URL("../src/components/workpanel/WorkPanel.tsx", import.meta.url),
- "utf8",
-);
-const sideChatTab = await readFile(
- new URL("../src/components/workpanel/SideChatTab.tsx", import.meta.url),
- "utf8",
-);
-const transcript = await readTranscriptSource();
-
-const entry = (sessionId, parentSessionId, createdAt, anchorMessageId) =>
- sideChatEntry({
- sessionId,
- parentSessionId,
- title: `Side chat: ${parentSessionId}`,
- createdAt,
- ...(anchorMessageId ? { anchorMessageId } : {}),
- });
-
-test("a side-chat tab is keyed by its child session", () => {
- const tab = sideChatWorkPanelTab("child-1");
- assert.equal(tab.id, `${SIDE_CHAT_TAB_PREFIX}child-1`);
- assert.equal(tab.id, "sidechat:child-1");
- assert.equal(tab.kind, "sidechat");
- assert.equal(tab.resource, "child-1");
- assert.equal(isKnownWorkPanelTab(tab), true);
- assert.equal(sideChatTabSessionId(tab), "child-1");
- assert.equal(isSideChatTab(tab), true);
-});
-
-test("only side-chat tabs resolve to a child session", () => {
- assert.equal(sideChatTabSessionId({ id: "review", kind: "review" }), null);
- assert.equal(sideChatTabSessionId(null), null);
- assert.equal(
- sideChatTabSessionId({ id: "sidechat:", kind: "sidechat", resource: " " }),
- null,
- );
-});
-
-test("registering and releasing a side chat keeps map identity stable", () => {
- const empty = {};
- const first = registerSideChat(empty, entry("child-1", "parent", 1));
- assert.deepEqual(sideChatSessionIds(first), ["child-1"]);
- assert.equal(removeSideChat(first, "missing"), first);
- assert.equal(removeSideChat(empty, "child-1"), empty);
- assert.deepEqual(removeSideChat(first, "child-1"), {});
-});
-
-test("deleting a session releases its own side chats and those opened from it", () => {
- const chats = registerSideChat(
- registerSideChat(
- registerSideChat({}, entry("child-1", "parent", 1)),
- entry("child-2", "other-parent", 2),
- ),
- entry("deep", "child-1", 3),
- );
- assert.deepEqual(
- sideChatSessionIds(removeSideChatsForSessions(chats, ["child-1"])).sort(),
- ["child-2"],
- );
- assert.deepEqual(
- sideChatSessionIds(removeSideChatsForSessions(chats, ["parent"])).sort(),
- ["child-2"],
- );
- assert.equal(removeSideChatsForSessions(chats, ["unrelated"]), chats);
-});
-
-test("side chats are listed for their own conversation, newest first", () => {
- const chats = registerSideChat(
- registerSideChat(
- registerSideChat({}, entry("older", "parent", 10)),
- entry("newer", "parent", 20),
- ),
- entry("elsewhere", "other-parent", 30),
- );
- assert.deepEqual(
- sideChatsForParent(chats, "parent").map((chat) => chat.sessionId),
- ["newer", "older"],
- );
- assert.deepEqual(sideChatsForParent(chats, undefined), []);
-});
-
-test("side-chat drafts and durable children share the panel surface", () => {
- assert.match(store, /pending: true/);
- assert.match(store, /commitForkedSession\(child, \{ activate: false, clearError: true \}\)/);
- assert.match(panel, /<SideChatTab sessionId=\{sessionId\} \/>/);
-});
-
-test("a side chat streams through the shared background projection", () => {
- assert.match(store, /function projectTranscriptEvent\(/);
- assert.match(store, /function projectSideChatEvent\(envelope: AgentEventEnvelope\): void \{/);
- assert.match(store, /if \(!state\.sideChats\[envelope\.sessionId\]\) return;/);
- assert.match(store, /projectSideChatEvent\(envelope\);/);
- assert.match(store, /sideChatTranscripts: \{/);
-});
-
-test("closing the panel releases the side chat and keeps the child session", () => {
- assert.match(store, /const releasedSessionId = sideChatTabSessionId\(closedTab\)/);
- assert.match(store, /removeSideChat\(state\.sideChats, releasedSessionId\)/);
- assert.match(store, /closeSideChat: \(sessionId\) => \{/);
- // The child is durable: releasing never deletes the session.
- assert.doesNotMatch(
- store.slice(store.indexOf("closeSideChat: (sessionId) => {"), store.indexOf("addSideChatReplyToMain: (sessionId) =>")),
- /api\.deleteSession/,
- );
-});
-
-test("the panel can stop the child and quote its answer into the main chat", () => {
- assert.match(store, /abortSession: async \(sessionId\) => \{/);
- assert.match(store, /await api\.abort\(sessionId\)/);
- assert.match(sideChatTab, /abortSession\(sessionId\)/);
- assert.match(store, /addSideChatReplyToMain: \(sessionId\) => \{/);
- assert.match(store, /get\(\)\.quoteMessageIntoComposer\(\{ title: entry\.title, text: answer\.content \}\)/);
- // Send targets the child session and never the visible one.
- assert.match(sideChatTab, /sendSideChatPrompt\(sessionId\)/);
- assert.match(sideChatTab, /t\("sideChat\.placeholder"\)/);
- assert.match(sideChatTab, /t\("sideChat\.empty"\)/);
-});
-
-test("promoting a side chat activates it and releases the panel entry", () => {
- assert.match(sideChatTab, /const openAsConversation = async \(\) => \{/);
- assert.match(sideChatTab, /closeSideChat\(sessionId\);\s*\n\s*await selectSession\(sessionId\)/);
-});
-
-test("a question from the child session is answerable inside the panel", () => {
- // The card resolves the request's own session id, so the docked panel can
- // answer the child without activating it.
- assert.match(sideChatTab, /<AskToolCard request=\{pendingAsk\} queued=\{queuedAsks\} \/>/);
- assert.match(sideChatTab, /askPending=\{Boolean\(pendingAsk\)\}/);
- assert.match(store, /resolveAsk: async \(sessionId, resolution: AskToolResolution\) => \{/);
-});
-
-test("the optimistic prompt row reaches an open side-chat panel", () => {
- const insert = store.slice(
- store.indexOf("function insertOptimisticUserMessage"),
- store.indexOf("function projectTranscriptEvent"),
- );
- assert.match(insert, /if \(state\.sideChatTranscripts\[sessionId\]\) \{/);
- const retract = store.slice(
- store.indexOf("function retractOptimisticUserMessage"),
- store.indexOf("function projectTranscriptEvent"),
- );
- assert.match(retract, /state\.sideChatTranscripts\[sessionId\]\?\.includes\(message\)/);
-});
-
-test("the docked transcript is a read-only projection of the child", () => {
- // Every row action resolves against the ACTIVE session, so a panel that
- // rendered them could re-page, truncate, or edit the visible conversation.
- assert.match(sideChatTab, /<TranscriptReadOnlyContext\.Provider value>/);
- assert.match(transcript, /export const TranscriptReadOnlyContext = createContext\(false\)/);
- assert.match(transcript, /const transcriptReadOnly = useContext\(TranscriptReadOnlyContext\)/);
- assert.match(transcript, /!editing && !transcriptReadOnly && \(hasAnswer \|\| showRevisionPager\)/);
- assert.match(transcript, /\(content \|\| hasError\) && actionMessage && !transcriptReadOnly/);
- // The panel owns one permission card, so the transcript must not add a second.
- assert.match(transcript, /\{pendingPermission && !transcriptReadOnly \? \(/);
-});
-
-test("the panel projection follows every event, even while the child is visible", () => {
- const callSites = store.match(/projectSideChatEvent\(envelope\);/g) ?? [];
- assert.equal(callSites.length, 1);
- // It must run before the cross-session early return, otherwise switching to the
- // child and back would leave a hole in the docked transcript.
- assert.ok(
- store.indexOf("projectSideChatEvent(envelope);") <
- store.indexOf("if (envelope.sessionId !== get().activeSessionId) {"),
- );
-});
-
-test("deleting a session strips its side-chat tab from every panel context", () => {
- const deletion = store.slice(
- store.indexOf("removeSideChatsForSessions(state.sideChats, [id])"),
- );
- assert.match(deletion, /const releasedTabIds = new Set\(/);
- assert.match(deletion, /const stripTabs = \(tabs: WorkPanelTab\[\]\) =>/);
- assert.match(deletion, /workPanelContexts = Object\.fromEntries\(/);
- assert.match(deletion, /workPanelTabs,/);
-});
-
-test("draft promotion preserves each panel context", () => {
- assert.match(store, /workPanelContexts: Object.fromEntries/);
- assert.match(store, /replaceTabs\(context.tabs\)/);
-});
diff --git a/apps/desktop/test/transcript-style.test.mjs b/apps/desktop/test/transcript-style.test.mjs
index df374ec6a..35a59014b 100644
--- a/apps/desktop/test/transcript-style.test.mjs
+++ b/apps/desktop/test/transcript-style.test.mjs
@@ -248,7 +248,7 @@ test("editing a user prompt regenerates it and keeps the old branch reachable",
assert.doesNotMatch(transcriptSource, /editAssistantMessage/);
assert.doesNotMatch(storeSource, /editAssistantMessage/);
// Slash prompts edit their typed form so the resend re-expands the template.
- assert.match(transcriptSource, /const editSeed = \(editableUserMessage && message\.command\) \|\| requestTextWithoutAnnotations\(message\.content/);
+ assert.match(transcriptSource, /const editSeed =\s*\(editableUserMessage && message\.command\) \|\| \(message\.content \|\| ""\);/);
// Same branch mechanics as regenerate, so main archives the replaced turn
// as a revision the pager can walk back to.
assert.match(storeSource, /editUserMessage:\s*async \(messageId, content, attachments\)/);
diff --git a/apps/desktop/test/turn-outcome-card.test.mjs b/apps/desktop/test/turn-outcome-card.test.mjs
index 03371f97e..7196770dc 100644
--- a/apps/desktop/test/turn-outcome-card.test.mjs
+++ b/apps/desktop/test/turn-outcome-card.test.mjs
@@ -47,8 +47,8 @@ test("outcome card exposes one localized continuation action", () => {
assert.doesNotMatch(outcome, /toolWorkPanelTab/);
assert.match(
sendPrompt,
- // The send ships the composed prompt so annotations travel with it (D-LOCAL-response-annotations).
- /await api\.prompt\(\{[\s\S]*?sessionId,[\s\S]*?content: outgoing,/,
+ // The send ships the submitted content through the prompt call.
+ /await api\.prompt\(\{[\s\S]*?sessionId,[\s\S]*?content,/,
);
assert.match(sendPrompt, /latestTurnResults: withoutRecordKey/);
assert.doesNotMatch(sendPrompt, /truncateFromMessageId/);
diff --git a/apps/desktop/test/upstream-sync-annotations.test.mjs b/apps/desktop/test/upstream-sync-annotations.test.mjs
deleted file mode 100644
index 4261f6aab..000000000
--- a/apps/desktop/test/upstream-sync-annotations.test.mjs
+++ /dev/null
@@ -1,293 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { runInNewContext } from "node:vm";
-import test from "node:test";
-import ts from "typescript";
-import * as annotations from "../src/lib/response-annotations.ts";
-import * as queued from "../src/lib/queued-prompts.ts";
-import * as sideChats from "../src/lib/side-chat.ts";
-import * as tabs from "../src/lib/work-panel-tabs.ts";
-import * as resize from "../src/lib/work-panel-resize.ts";
-import * as panes from "../src/lib/session-panes.ts";
-
-// Execute the real domain factories with a fake host; no app, database, or model.
-function load(path, imports) {
- const source = readFileSync(new URL(path, import.meta.url), "utf8");
- const { outputText } = ts.transpileModule(source, {
- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX },
- });
- const module = { exports: {} };
- new Function("require", "exports", "module", outputText)((id) => {
- assert.ok(Object.hasOwn(imports, id), `unexpected dependency ${id}`);
- return imports[id];
- }, module.exports, module);
- return module.exports;
-}
-const annotation = (id) => annotations.responseAnnotation({ id, messageId: `message-${id}`, text: `excerpt ${id}` });
-const deferred = () => {
- let resolve, reject;
- const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
- return { promise, resolve, reject };
-};
-function queueHarness({ running = true, materialize } = {}) {
- const ack = deferred();
- const calls = [];
- const notices = [];
- const state = {
- activeSessionId: "s1", pendingPlans: {}, runningSessions: { s1: running },
- responseAnnotations: { s1: [annotation("a1"), annotation("a2")], s2: [annotation("other")] },
- sessions: [{ id: "s1", title: "Title" }], messages: [], queuedPrompts: {},
- latestTurnResults: {}, sessionOutcomes: {}, sideChats: {}, sideChatTranscripts: {},
- showToast: (...args) => notices.push(args),
- };
- const access = {
- get: () => state,
- set: (update) => Object.assign(state, typeof update === "function" ? update(state) : update),
- };
- const { createQueueSlice } = load("../src/stores/slices/queue-slice.ts", {
- i18next: { default: { t: (key) => key } },
- "../../lib/api": { api: {
- queuePrompt: (request) => { calls.push(request); return ack.promise; },
- prompt: (request) => { calls.push(request); return ack.promise; },
- listQueuedPrompts: async () => ({ entries: [] }),
- } },
- "../../lib/response-annotations": annotations,
- "../../lib/queued-prompts": queued,
- "../../lib/session-transcript": { optimisticUserMessage: (id, content) => ({ id, role: "user", content }) },
- });
- Object.assign(state, createQueueSlice({
- ...access,
- runtime: {
- sessionTranscriptCache: new Map(), submittedComposerDrafts: new Map(),
- beginNavigationIntent: () => 1,
- insertOptimisticUserMessage: (_, message) => state.messages.push(message),
- retractOptimisticUserMessage: (_, message) => { state.messages = state.messages.filter((item) => item !== message); },
- },
- materializeDraftSession: () => materialize(),
- promptAttachmentsFromDraft: () => [],
- withoutRecordKey: (record, key) => Object.fromEntries(Object.entries(record).filter(([id]) => id !== key)),
- isDefaultSessionTitle: () => false,
- viewingSessionIdForPrompt: () => "s1",
- messageErrorFromUnknown: (error) => ({ code: "TEST", message: error.message }),
- assistantErrorMessage: (error) => ({ role: "assistant", error }),
- }));
- return { state, ack, calls, notices };
-}
-
-for (const running of [true, false]) {
- test(`${running ? "queue" : "send"} consumes only acknowledged unchanged annotations in the originating session`, async () => {
- const { state, ack, calls } = queueHarness({ running });
- const submitted = [...state.responseAnnotations.s1];
- const send = state.sendPrompt("request", { text: "request", fileReferences: [] });
- assert.equal(calls.length, 1);
- assert.equal(state.responseAnnotations.s1.length, 2, "must not consume before acknowledgement");
- assert.equal(calls[0].content, annotations.responseAnnotationPrompt("request", submitted));
- const edited = { ...submitted[1], annotation: "edited while waiting" };
- const added = annotation("new");
- state.responseAnnotations.s1 = [submitted[0], edited, added];
- state.activeSessionId = "s2";
- ack.resolve({ id: "queue-1" });
- assert.equal(await send, true);
- assert.deepEqual(state.responseAnnotations.s1, [edited, added]);
- assert.equal(state.responseAnnotations.s2[0].id, "other");
- });
-
- test(`${running ? "queue" : "send"} failure retains annotations and reports rejection`, async () => {
- const { state, ack, notices } = queueHarness({ running });
- const before = state.responseAnnotations.s1;
- const send = state.sendPrompt("", { text: "", fileReferences: [] });
- ack.reject(new Error("host refused"));
- assert.equal(await send, false);
- assert.equal(state.responseAnnotations.s1, before);
- if (running) {
- assert.equal(notices[0][0], "host refused");
- assert.equal(state.queuedPrompts.s1?.length ?? 0, 0);
- } else assert.equal(state.latestTurnResults.s1.status, "failed");
- });
-}
-
-test("ordinary queued text still waits for host acceptance without annotations", async () => {
- const { state, ack, calls } = queueHarness();
- state.responseAnnotations = {};
- const send = state.sendPrompt("plain", { text: "plain", fileReferences: [] });
- assert.equal(calls[0].content, "plain");
- ack.resolve({ id: "queue-1" });
- assert.equal(await send, true);
- assert.deepEqual(state.responseAnnotations, {});
-});
-
-for (const withOtherTab of [false, true]) {
- test(`closing side chat ${withOtherTab ? "beside another tab" : "as final tab"} preserves upstream launcher and durable child`, () => {
- const child = sideChats.sideChatWorkPanelTab("child");
- const other = tabs.toolWorkPanelTab("review");
- const state = {
- activeSessionId: "parent", workPanelOpen: true,
- workPanelTabs: withOtherTab ? [child, other] : [child], activeWorkPanelTabId: child.id,
- workPanelFileRequest: null, workPanelContexts: {},
- sideChats: { child: { sessionId: "child", parentSessionId: "parent" }, unrelated: { sessionId: "unrelated" } },
- sideChatTranscripts: { child: [], unrelated: [] }, sessions: [{ id: "child" }],
- };
- const { createWorkPanelSlice } = load("../src/stores/slices/work-panel-slice.ts", {
- "../../lib/api": { api: {} }, "../../lib/side-chat": sideChats,
- "../../lib/work-panel-tabs": tabs, "../../lib/work-panel-resize": resize,
- });
- const actions = createWorkPanelSlice({ get: () => state, set: (update) => Object.assign(state, typeof update === "function" ? update(state) : update), isSessionSelectionPending: () => false });
- actions.closeWorkPanelTab(child.id);
- assert.equal(state.workPanelOpen, true);
- assert.equal(state.activeWorkPanelTabId, withOtherTab ? other.id : null);
- assert.equal(state.sideChats.child, undefined);
- assert.equal(state.sideChatTranscripts.child, undefined);
- assert.ok(state.sideChats.unrelated);
- assert.ok(state.sideChatTranscripts.unrelated);
- assert.deepEqual(state.sessions, [{ id: "child" }]);
- assert.deepEqual(state.workPanelContexts.parent.tabs, withOtherTab ? [other] : []);
- });
-}
-
-test("failed submission draft restoration never overwrites newer input or another session", () => {
- const source = readFileSync(new URL("../src/features/chat/composer/hooks/useComposerDraft.ts", import.meta.url), "utf8");
- const body = source.match(/const restoreDraftForKey = \(key: string, snapshot: ComposerDraftSnapshot\) => \{[\s\S]*?\n \};/)[0];
- const code = ts.transpileModule(body, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- for (const [active, newer] of [["s1", "new input"], ["s2", "cached input"], ["s2", ""]]) {
- const writes = [], values = [];
- const snapshot = { text: "failed draft", fileReferences: [] };
- runInNewContext(code + '; restoreDraftForKey("s1", snapshot);', {
- snapshot, useAppStore: { getState: () => ({ activeSessionId: active }) },
- draftKeyForSession: (id) => id, readComposerDraft: () => ({ text: newer }),
- writeComposerDraft: (...args) => writes.push(args), valueRef: { current: newer },
- setValue: (value) => values.push(value), setFileReferences() {}, setCursor() {},
- });
- assert.deepEqual(values, []);
- assert.equal(writes.length, active === "s2" && !newer ? 1 : 0);
- }
-});
-
-test("user row edit seed and queue preview hide only the generated annotation block", () => {
- const row = readFileSync(new URL("../src/features/chat/transcript/MessageRow.tsx", import.meta.url), "utf8");
- const status = readFileSync(new URL("../src/features/chat/composer/ComposerStatus.tsx", import.meta.url), "utf8");
- const editSeed = row.match(/const editSeed = ([^;]+);/)[1];
- const label = status.match(/const label =([\s\S]*?);/)[1];
- for (const request of ["plain text", "", "Explain this:\n## My request: extra"]) {
- for (const content of [request, annotations.responseAnnotationPrompt(request, [annotation("a1")])]) {
- const context = { requestTextWithoutAnnotations: annotations.requestTextWithoutAnnotations, message: { content }, editableUserMessage: true };
- assert.equal(runInNewContext(editSeed, context), request);
- assert.equal(runInNewContext(label, { ...context, item: { content, draft: { fileReferences: [] } }, t: () => "empty" }), request || "empty");
- }
- }
-});
-
-test("side-chat and background projections share upstream delta accumulation, including while the child is active", async () => {
- const shared = await import("@pi-desktop/shared");
- const transcript = await import("../src/lib/session-transcript.ts");
- const { createSessionRuntime } = load("../src/stores/runtime/session-runtime.ts", {
- "@pi-desktop/shared": shared,
- "../../lib/api": { api: {} },
- "../../lib/navigation-intent": { createNavigationIntentController: () => ({}) },
- "../../lib/session-transcript": transcript,
- "../../lib/sidebar-preferences": {},
- "../../lib/sidebar-session-groups": {},
- "../../lib/tool-display": { formatToolValue: JSON.stringify },
- "../../lib/session-panes": panes,
- });
- const state = {
- activeSessionId: "child", messages: [], retainedTranscripts: {}, sessionHistory: {},
- sideChats: { child: {} }, sideChatTranscripts: { child: [] },
- };
- const runtime = createSessionRuntime({ get: () => state, set: (update) => Object.assign(state, typeof update === "function" ? update(state) : update) });
- runtime.cacheSessionTranscript("child", []);
- const envelope = (event) => ({ sessionId: "child", event, ts: 1000 });
- const message = { id: "m1", role: "assistant", content: "", status: "streaming" };
- for (const event of [
- { type: "message_start", message },
- { type: "message_update", stream: "delta", deltaText: "first ", message },
- { type: "message_update", stream: "delta", deltaText: "second", message },
- ]) {
- runtime.projectSideChatEvent(envelope(event));
- runtime.cacheBackgroundTranscriptEvent(envelope(event));
- }
- assert.equal(state.sideChatTranscripts.child[0].content, "first second");
- assert.deepEqual(runtime.sessionTranscriptCache.get("child"), state.sideChatTranscripts.child);
- const optimistic = { id: "prompt", role: "user", content: "follow up" };
- runtime.insertOptimisticUserMessage("child", optimistic);
- assert.ok(state.sideChatTranscripts.child.includes(optimistic));
- runtime.retractOptimisticUserMessage("child", optimistic);
- assert.ok(!state.sideChatTranscripts.child.includes(optimistic));
- delete state.sideChats.child;
- const before = state.sideChatTranscripts.child;
- runtime.projectSideChatEvent(envelope({ type: "message_update", stream: "delta", deltaText: "ignored", message }));
- assert.equal(state.sideChatTranscripts.child, before);
-});
-
-test("delayed acknowledgement blocks repeat Enter for one session but not another, then releases", async () => {
- const { state, ack, calls } = queueHarness();
- const first = state.sendPrompt("", { text: "", fileReferences: [] });
- assert.equal(await state.sendPrompt("", { text: "", fileReferences: [] }), false);
- assert.equal(calls.length, 1);
- assert.equal(state.responseAnnotations.s1.length, 2);
- state.runningSessions.s2 = true;
- const other = state.sendPrompt("other", { text: "other", fileReferences: [] }, "s2");
- assert.equal(calls.length, 2);
- ack.resolve({ id: "queue-1" });
- assert.equal(await first, true);
- assert.equal(await other, true);
- assert.equal(await state.sendPrompt("next", { text: "next", fileReferences: [] }), true);
- assert.equal(calls.length, 3);
-});
-
-test("queue rejection releases the submission guard so a deliberate later attempt can run", async () => {
- const { state, ack, calls } = queueHarness();
- const first = state.sendPrompt("request");
- ack.reject(new Error("rejected"));
- assert.equal(await first, false);
- assert.equal(await state.sendPrompt("retry"), false);
- assert.equal(calls.length, 2, "second rejection came from a real attempt, not a stuck guard");
-});
-
-test("unexpected pre-host failure returns false and releases the submission guard", async () => {
- const { state, ack, calls } = queueHarness();
- const original = state.enqueuePrompt;
- state.enqueuePrompt = async () => { throw new Error("unexpected failure"); };
- assert.equal(await state.sendPrompt("request"), false);
- state.enqueuePrompt = original;
- ack.resolve({ id: "queue-1" });
- assert.equal(await state.sendPrompt("retry"), true);
- assert.equal(calls.length, 1);
-});
-
-test("draft submissions are fenced during materialization and after adopting their new session", async () => {
- const creation = deferred();
- let creates = 0;
- const { state, ack, calls } = queueHarness({ materialize: () => { creates++; return creation.promise; } });
- state.activeSessionId = undefined;
- const first = state.sendPrompt("draft");
- assert.equal(await state.sendPrompt("repeat draft"), false);
- assert.equal(creates, 1);
- state.activeSessionId = "s1";
- creation.resolve("s1");
- await Promise.resolve();
- assert.equal(await state.sendPrompt("repeat created"), false);
- assert.equal(calls.length, 1);
- ack.resolve({ id: "queue-1" });
- assert.equal(await first, true);
- assert.equal(await state.sendPrompt("next"), true);
- assert.equal(calls.length, 2);
-});
-
-test("upstream input routes Alt+Enter to steering, Shift+Enter to newline, and ignores IME confirmation", () => {
- const jsx = (type, props) => ({ type, props });
- const { ComposerInput } = load("../src/features/chat/composer/ComposerInput.tsx", {
- react: {}, "react/jsx-runtime": { jsx, jsxs: jsx },
- "./editor": {},
- });
- const submits = [];
- const tree = ComposerInput({ value: "text", runActive: true, enterToSend: true,
- composerAc: { close() {}, open: false, hasItems: false }, onSubmit: (steer) => submits.push(steer) });
- const input = tree.props.children.props.children[0];
- const key = (overrides) => input.props.onKeyDown({ key: "Enter", nativeEvent: {}, preventDefault() {}, ...overrides });
- key({ altKey: true });
- key({ shiftKey: true });
- key({ nativeEvent: { isComposing: true }, altKey: true });
- key({ nativeEvent: { keyCode: 229 }, altKey: true });
- key({});
- assert.deepEqual(submits, [true, undefined]);
-});
diff --git a/docs/adr/0254-native-pi-session-continuation.md b/docs/adr/0254-native-pi-session-continuation.md
index 22cab0ace..502f61ce3 100644
--- a/docs/adr/0254-native-pi-session-continuation.md
+++ b/docs/adr/0254-native-pi-session-continuation.md
@@ -32,6 +32,10 @@ PI-Desktop historically imports Pi sessions by flattening them into Desktop-owne
## Amendment: native side-chat forks (2026-09-14)
+The `sidechat:` panel and tab described in this amendment were removed by ADR
+0268; the `session.fork` capability they routed to remains in place and is used
+by the Fork action.
+
`session/fork` is now source-discriminated. Desktop sources keep the existing
Rust `session.fork` contract; `native-pi:` sources route to a sidecar
`native.session.fork`, which returns the child as an ordinary `SessionDetail`.
diff --git a/docs/adr/0268-remove-quotes-annotations-and-side-chats.md b/docs/adr/0268-remove-quotes-annotations-and-side-chats.md
new file mode 100644
index 000000000..f06c46140
--- /dev/null
+++ b/docs/adr/0268-remove-quotes-annotations-and-side-chats.md
@@ -0,0 +1,138 @@
+# ADR 0268: Remove quotes, annotations, and side chats
+
+- Status: Accepted
+- Date: 2026-09-16
+- Deciders: PI-Desktop runtime and desktop UI maintainers
+- Supersedes: ADR message-quotes-and-side-chats, ADR response-annotations, ADR floating-annotation-index
+- Amends: ADR 0254 (its "Amendment: native side-chat forks", 2026-09-14)
+- Preserves: D097, D128, D134, D209, D254, D261, D301
+- Related: [04-ux/08-component-spec.md](../spec/04-ux/08-component-spec.md) ·
+ [04-ux/09-interaction-patterns.md](../spec/04-ux/09-interaction-patterns.md) ·
+ [06-delivery/04-e2e-test-plan.md](../spec/06-delivery/04-e2e-test-plan.md)
+
+## Context
+
+Three renderer-owned surfaces grew around the transcript and the composer. ADR
+message-quotes-and-side-chats added a **Quote** action to the message action
+row, a selected-text overlay, and renderer-owned side chats docked in the work
+panel. ADR response-annotations turned Add to chat on an assistant turn into a
+numbered annotation attachment carried to the model in a generated
+`# Response annotations:` prompt block, and ADR floating-annotation-index added
+the floating index, source badges and highlights, and the comment editor. ADR
+0254's native side-chat fork amendment made those panels work for `native-pi:`
+sessions.
+
+Together they are more surface than the product uses. The overlay and the action
+row both had to recover an excerpt from the rendered DOM; annotations added a
+second prompt serialization that every display surface (transcript, edit seed,
+queue preview) has to reverse; and a side chat is a second session lifecycle
+whose only durable artifact — the forked child — `session.fork` already
+produces. Copy, edit, fork, and retry cover the rest.
+
+## Decision
+
+1. **Message action row.** Remove **Quote**, **Annotate**, and **Open/Ask in
+ side chat** from the hover action row of user messages and assistant turns.
+ Copy, Edit and Delete (user messages), Fork, and Retry/Regenerate stay
+ unchanged in place, behavior, labels, and shortcuts.
+2. **Selection overlay.** Remove the selected-text toolbar entirely: selecting
+ text in the transcript no longer floats an action strip. Delete
+ `lib/selection-quote.ts`, `lib/chat-quotes.ts`, the `SelectionQuoteButton`
+ component and its styles. The composer keeps no quote-prefill path:
+ `appendComposerDraftText` and `quoteMessageIntoComposer` and their store
+ action go away.
+3. **Annotations.** Remove annotations as a feature: the comment editor, the
+ floating annotation index, the answer source badges and highlights, the
+ composer annotation attachment chip, the annotation store slice, and the
+ annotation anchor modules are deleted. A `:codex-annotation{index="N"}`
+ directive in an answer is no longer recognized; it renders as the ordinary
+ Markdown text it is.
+4. **Prompt assembly.** The send path no longer composes a
+ `# Response annotations:` block: `api.prompt` and `enqueuePrompt` use the
+ user's text as written, with no generated heading, instruction sentence, or
+ `<response-annotations>` payload. The display-layer reduction
+ `requestTextWithoutAnnotations` is deleted with it, so an older stored prompt
+ that already contains the generated block is shown verbatim in the
+ transcript, in edit seeds, and in queue previews instead of being reduced
+ back to the request.
+5. **Side chats.** Remove side chats as a feature: the first-Send draft
+ lifecycle that created the child session, the renderer transcript projection
+ (`projectSideChatEvent`), the `sidechat:` work-panel tab type and its
+ `SideChatTab`, the registration / release / cascade-cleanup rules, and the
+ availability blocked-reason reporting are all deleted. `session.fork` stays
+ as a capability and the Fork action stays as its only entry point.
+6. **Retired identifiers (retired; must never be reused).** Decision IDs
+ `D-LOCAL-message-quotes`, `D-LOCAL-selection-overlay`,
+ `D-LOCAL-response-annotations`, `D-native-sidechat-stream`, and E2E IDs
+ `E2E-CHAT-quote-prefill`, `E2E-CHAT-selection-markdown`,
+ `E2E-CHAT-selection-side-chat`, `E2E-CHAT-annotation-attachments`,
+ `E2E-CHAT-annotation-session-state`, `E2E-CHAT-annotation-source-index`,
+ `E2E-CHAT-annotation-ack-and-steering`, `E2E-CHAT-side-chat-fork`,
+ `E2E-CHAT-side-chat-stream`, `E2E-CHAT-side-chat-add-to-main`,
+ `E2E-CHAT-side-chat-promote`, `E2E-CHAT-side-chat-close`, and
+ `E2E-SESSION-native-side-chat-fork-survives-close` are retired and must
+ never be reused for another scenario. The superseded ADR files stay on disk
+ as history.
+7. **Boundaries.** The host protocol stays v11 and the storage schema stays
+ v15: no new IPC channel, no new permission, no protocol or schema bump, and
+ no Rust change. `session.fork`, the transcript, the work panel, and the rest
+ of the composer keep their existing contracts.
+
+## Preserved behavior
+
+- **D134 / `session.fork`.** Fork still resolves a durable child from an anchor
+ message and still activates it, including the `native-pi:` route of ADR 0254;
+ ADR 0023 is unchanged. Side chats were a consumer of it, not a part of it.
+- **D209 / D301.** Smart Stop still restores the unanswered send's draft, and
+ per-session draft slots are untouched. With no prefill and no annotation
+ snapshot beside the draft, both paths simply have less to carry.
+- **D097 / D128 / D254 / D261.** The work panel keeps role, sizing, identity
+ keying, neighbor-close, and per-session switching; losing the `sidechat:` tab
+ type removes one resource kind, not the model. Transcript reading ownership
+ and the bounded expansion history window are unchanged.
+- **The rest of the action row.** Copy, Edit, Delete, Retry/Regenerate, and
+ Fork keep their current behavior, tooltips, and accessible names.
+- **Child sessions already created.** A session forked earlier from a side chat
+ stays an ordinary session in the sidebar, lists, search, and stored history.
+
+## Consequences
+
+- A user loses the shortcut of reusing an earlier prompt or answer inside the
+ composer, and loses the panel for asking a side question beside the main
+ conversation; reassembling either means copying text or forking a session and
+ switching to it.
+- A stored prompt written while annotations were enabled can show the generated
+ `# Response annotations:` heading and payload as plain text, because every
+ display surface now renders the stored string unchanged.
+- The renderer sheds roughly 2000 lines — the overlay, quote recovery,
+ annotation editor, index, badges, and the whole side-chat lifecycle — plus
+ eleven unit-test files and their E2E scenarios.
+- Nothing moves across a process boundary: protocol v11, schema v15, the IPC
+ surface, the permission set, and the Rust host are untouched.
+
+## Alternatives considered
+
+### Hide the entry points and keep the code
+
+Rejected: dead branches would still own store slices, i18n keys, CSS, and the
+generated-block parser, and every later change to the action row or the send
+path would have to keep them compiling for nobody.
+
+### Keep a display-layer compatibility downgrade
+
+Rejected: keeping `requestTextWithoutAnnotations` and the directive parser alive
+only to prettify old prompts would preserve exactly the second serialization
+this ADR removes, and a stored prompt that is not sent is harmless as text.
+Old transcripts are readable without it.
+
+### Remove annotations and side chats, keep quotes and the selection overlay
+
+Rejected: the overlay, the quote recovery path, and the composer prefill are the
+largest single block of renderer-only code here, and quoting a whole message or
+a sentence has an exact substitute in the OS clipboard and the composer.
+
+### Turn side chats into an ordinary child-session tab instead of deleting them
+
+Rejected: that is Fork plus the existing session list; a new docked tab kind
+would keep the registration, projection, and cleanup lifecycle while adding a
+fourth way to reach the same durable child.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 69f967352..8e19f33c9 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -242,9 +242,9 @@ Each ADR includes:
| 0220 | Keep Windows work-panel chrome single-purpose | Accepted (amends D154 / D357 / ADR 0195) |
| 0221 | Render canonical thinking-level values without translation | Accepted (amends D369 / ADR 0202) |
| 0222 | Native file and folder drops in the Composer | Accepted (amends ADR 0101 / D397) |
-| message-quotes-and-side-chats | Message quotes and renderer-owned side chats | Accepted (preserves D097 / D128 / D134 / D154; amended by D-LOCAL-selection-overlay) |
-| response-annotations | Response annotations as prompt attachments | Accepted (amends D-LOCAL-message-quotes decision 3 for assistant turns; presentation amended by floating-annotation-index) |
-| floating-annotation-index | Floating annotation index and source locations | Accepted (amends D-LOCAL-response-annotations / response-annotations) |
+| message-quotes-and-side-chats | Message quotes and renderer-owned side chats | Superseded by 0268 |
+| response-annotations | Response annotations as prompt attachments | Superseded by 0268 |
+| floating-annotation-index | Floating annotation index and source locations | Superseded by 0268 |
| 0223 | Context Usage Display Preference | Accepted (amends 0184) |
| 0224 | Right panel tab strip and data-driven add menu | Accepted (issue #229) |
| 0225 | Restore deferred tools from effective session context | Accepted (issue #225) |
@@ -294,3 +294,4 @@ Each ADR includes:
| transcript-reading-ownership | [Share renderer history and search views](transcript-reading-ownership.md) | Accepted |
| 0266 | [Plugin fs roots follow the calling session](0266-plugin-fs-root-follows-the-calling-session.md) | Accepted (D093) |
| 0267 | [Plugin labels follow the app language](0267-plugin-labels-follow-the-app-language.md) | Accepted (amends 0160; ADR 0182) |
+| 0268 | Remove quotes, annotations, and side chats | Accepted (supersedes message-quotes-and-side-chats / response-annotations / floating-annotation-index) |
diff --git a/docs/adr/floating-annotation-index.md b/docs/adr/floating-annotation-index.md
index 1bee226e8..9f4778794 100644
--- a/docs/adr/floating-annotation-index.md
+++ b/docs/adr/floating-annotation-index.md
@@ -1,6 +1,7 @@
# ADR floating-annotation-index: Floating Annotation Index and Source Locations
+> Superseded by ADR 0268.
-- Status: Accepted
+- Status: Superseded by ADR 0268
- Date: 2026-09-12
- Amends: ADR response-annotations / D-LOCAL-response-annotations (annotation presentation and duplicate identity)
- Preserves: D209, D301, D261, D-LOCAL-selection-overlay; protocol v11 and schema v15
diff --git a/docs/adr/message-quotes-and-side-chats.md b/docs/adr/message-quotes-and-side-chats.md
index c186b3b37..c08310bb6 100644
--- a/docs/adr/message-quotes-and-side-chats.md
+++ b/docs/adr/message-quotes-and-side-chats.md
@@ -1,6 +1,7 @@
# ADR message-quotes-and-side-chats: Message Quotes and Renderer-Owned Side Chats
+> Superseded by ADR 0268.
-- Status: Accepted
+- Status: Superseded by ADR 0268
- Date: 2026-09-11
- Deciders: PI-Desktop runtime and desktop UI maintainers
- Amends: D209, D301
diff --git a/docs/adr/response-annotations.md b/docs/adr/response-annotations.md
index 1aa5744ed..23d165d44 100644
--- a/docs/adr/response-annotations.md
+++ b/docs/adr/response-annotations.md
@@ -1,6 +1,7 @@
# ADR response-annotations: Response Annotations as Prompt Attachments
+> Superseded by ADR 0268.
-- Status: Accepted; presentation and duplicate identity amended by ADR floating-annotation-index
+- Status: Superseded by ADR 0268
- Date: 2026-09-11
- Deciders: PI-Desktop runtime and desktop UI maintainers
- Amends: D-LOCAL-message-quotes decision 3 (for assistant turns)
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 1f0bce67b..a9d14ed2a 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -252,7 +252,7 @@ persisted marker protects accepted input from Smart Stop after renderer reload.
A native Pi `message_end` may additionally carry the optional additive
`replacesMessageId`: the provisional streaming row id whose durable SDK entry
this event publishes. The renderer re-keys exactly that row (active, cache,
-retained, side chat) and a generic event without the field leaves every other
+retained) and a generic event without the field leaves every other
row untouched. The field adds no event kind, RACP kind, or storage change.
A user `message_end` can additionally
carry `precedingAssistant`, a streaming snapshot that reserves the reply's
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index c567050a0..d154c6dcb 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1241,9 +1241,6 @@ device/inode/size/hash before it is projected or registered; an altered file
fails closed without returning a child. A fork is a data-only copy: it executes
no model and loads no project resources, so it stays available while the parent
is provider-unavailable or project-untrusted, without granting prompt
-readiness. The side-chat panel streams the child's provisional assistant row
-and re-keys exactly that row when persistence reports the durable SDK entry id
-through the additive `replacesMessageId` field.
ModelRuntime performs its public offline initialization to restore the local
catalog and auth snapshot. Native Composer readiness uses native `canPrompt`,
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index ba11bf384..f95382350 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -1436,8 +1436,8 @@ trust, saved-provider/auth, canonical-path, identity, and lease checks pass.
`AgentSession` and `SessionManager` append the native entries. Desktop host turn
and transcript append APIs are not invoked. Rename, delete, project move,
revision, Plan/Goal, collaboration, and queue operations remain unsupported
-for native sessions in this slice. Forking and ordinary text-only side-chat
-send/stop are supported as described here and in the runtime spec.
+for native sessions in this slice. Forking is supported as described here and in
+the runtime spec.
A native fork writes exactly one new v3 JSONL child in the parent's session
directory. Branch extraction runs against an in-memory manager over the parent
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 5f344eb4e..87c7319b1 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1097,83 +1097,6 @@ It does not render separate Details or Output tabs.
deleted delegation shows a localized unavailable state and never displays
another session's rows.
-### 5.8 Side chat (D-LOCAL-message-quotes)
-
-First-send lifecycle (Issue #421): opening creates only a renderer draft;
-no persistent child exists until the user sends nonempty content. Selection
-Ask in side chat only prefills a Markdown blockquote. Closing an unsent draft
-leaves no session record. Creation replaces the draft tab in its own parent's
-panel context; repeated sends cannot create duplicate children. Creation or
-send failure retains the draft; a created child is reused on retry. Promotion
-and Add to main chat are disabled for drafts.
-
-A side chat is one more work-panel resource: a live view of another session's
-transcript beside the main conversation, not a second panel and not a new kind
-of session.
-
-- Entry: **Open side chat** on an assistant turn (fork anchored at that assistant
- message) and on a user message (fork anchored at that user message), with the
- tooltip and accessible name `chat.startSideChat`. First Send calls the existing
- `session.fork` with the anchor and does not activate the child, so the main
- conversation keeps its visible session. The child is durable on the host
- exactly as an ordinary branch. For a native Pi parent the same channel is
- source-discriminated: the sidecar returns the child's whole anchored
- transcript, the panel streams its reply under a provisional row that is
- re-keyed to the durable SDK entry, and a native child that is read-only
- (provider/trust/external change) disables Send with the `sideChat.readOnly`
- hint, while a send during a running native turn is rejected before the
- Desktop queue with a visible toast and the draft kept. Stop always stays
- available for a running child.
-- Registration: the child is registered as a side chat of the parent session in
- renderer-owned state, and the panel opens one `sidechat` tab whose identity is
- `sidechat:<childSessionId>`. The tab reuses the upstream docked panel, its
- three-column width budget, resize lifecycle, tab strip/launcher, and the
- existing per-session panel-context rule (D128): changing the visible session
- swaps that session's retained context atomically.
-- Live content: while a side chat is registered, the child's message and tool
- start / update / end events are projected into a renderer-owned per-session
- transcript map from the same event stream the active transcript consumes,
- reusing the existing background-transcript reducer. The panel streams live
- although the child is never the active session.
-- Body: a compact header with the side-chat title (the tab label reuses
- `sideChat.title`), **Add to main chat** (`sideChat.addToMain`), **Open as a
- conversation** (`sideChat.openAsSession`), and the shared tab-close control;
- the child's transcript rendered with the existing transcript component; the
- existing permission card and ask card, each resolving by the request's own
- session id, so a child that needs approval or an answer never stalls behind an
- invisible prompt; and a compact input (placeholder
- `sideChat.placeholder`, empty-state line `sideChat.empty`) with Send reusing
- `chat.send` and Stop reusing `chat.stopGenerating`. Send targets the child
- through the existing prompt path; Stop aborts that child session.
-- Add to main chat copies the side chat's newest assistant answer into the main
- conversation's composer as a quote of that answer, under the Composer's quoted
- draft contract (§11.9) and its 2000-character cap, attributed to the side
- chat's title. It never sends.
-- Open as a conversation activates the child through the normal
- session-selection path, so the full composer, prompt queue, and stop controls
- apply, and releases the side-chat registration and its tab.
-- Close: closing the tab removes the registration and its transcript projection.
- Unsent drafts leave no session record. An existing child session is not
- deleted and keeps appearing in the sidebar, session
- lists, and search. Entries are removed when the tab closes, when the child is
- opened as a conversation, and when the parent or child session is deleted.
-- Boundaries: side-chat state is renderer-owned and is not persisted across
- restart (the durable child is). Native fork adds sidecar file creation but no
- host protocol, storage schema, permission change, or native queue: the child
- remains an ordinary Pi session in the sidebar, session lists, and title/
- project search, and it reopens as a normal conversation.
-
----
-
-#### Send availability
-
-Drafts use the parent session's live availability. A running/busy parent disables
-first Send with a visible explanation; a read-only parent also disables it.
-The submission action shares the same gate and reports blocked programmatic
-submissions without creating a child or clearing text. After creation, the
-submission action checks the child's current availability again before sending.
-Existing children keep their normal queue and Stop behavior. Recovery re-enables Send automatically.
-
## 6. SessionList
### 6.1 Purpose
@@ -1328,9 +1251,8 @@ storage but compose into one assistant turn until the next user message.
cancels pending follow work, and shows the "scroll to bottom" floating button;
stream or resize updates cannot pull the viewport back down; send / retry /
regenerate re-pins and jumps to bottom
-- Hover message: its action row appears — Copy, Quote, and the row's other
- per-turn actions. Quote prefills the composer per §11.9 and Open side chat
- opens §5.8; neither sends or leaves the visible session.
+- Hover message: its action row appears — Copy and the row's other per-turn
+ actions.
- Assistant fragments emitted before and after tool calls compose into one
`role="article"` turn. The turn exposes one trailing meta row and one action
toolbar; Copy joins all contentful fragments in order, while Fork and
@@ -1698,7 +1620,7 @@ message its checkpoint covers.
### 8.6 MVP constraints
-- No message reactions/annotations
+- No message reactions
- No edit user message (deferred)
- Copy assistant answer excludes thinking text
@@ -1821,54 +1743,6 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/shi
height derives from `--composer-dock-height`, which the composer republishes as
its draft grows, so dashes move without a marker change or a window resize.
-### 8.8 Quote and side-chat actions (D-LOCAL-message-quotes, D-LOCAL-selection-overlay)
-
-- Every user message exposes **Quote** in its hover action row beside Copy,
- Edit, and Delete; an assistant turn's row exposes the annotate action instead
- (§11.10, D-LOCAL-response-annotations). Activating Quote inserts a
- blockquote of the message into the active session's composer draft through the
- existing prefill contract and focuses the composer; it never sends, never
- creates a session, and writes nothing to the transcript.
-- **Open side chat** uses the same row with the `chat.startSideChat` label. It
- forks at that message and opens §5.8 without activating the child.
-- The excerpt is the live text selection when that selection is inside the
- clicked message row; otherwise it is the message's own text (for an assistant
- turn, its answer text). The inserted text follows the Composer contract in
- §11.9.
-- A non-empty selection inside a transcript row also floats **one** overlay
- above it, so the common case — quoting the sentence, formula, or table just
- read — needs no scroll to the end of the message. It is an action row of text
- buttons with hairline separators and the icon action last: **Add to chat**
- (`chat.addToChat`), **Ask in side chat** (`chat.askInSideChat`, disabled while
- the visible session runs), and **Copy** (`chat.copy`). It is centered on the
- selection, sits 8 px above it, is clamped into its bounds, and is portaled
- above the transcript in the body-portaled popover layer.
-- The overlay's bounds are the clipping ancestors' rects (the transcript
- scroller is one) intersected with the viewport, capped by the docked
- composer's top edge, which floats over the transcript. Scrolling the thread
- recomputes and follows the selection; scrolling something unrelated leaves the
- overlay alone. It also recomputes on selection change, double click, key up,
- pointer up, pointer cancel, and resize (at most once per frame), and it hides
- on a press outside it, on selection collapse, and after any action clears the
- native selection.
-- The selection must live in one message row: a drag that crosses rows raises no
- overlay, and a range that leaves the row is clamped back to it. The overlay is
- a transcript affordance, not a message one: a read-only projection (§5.8)
- never renders it, and never renders the row toolbars either.
-- The excerpt is recovered from the rendered DOM (D-LOCAL-selection-overlay), not from
- `Selection.toString()`: a formula quotes as `$…$` / `$$…$$` TeX from KaTeX's
- `application/x-tex` annotation (a partial formula selection is expanded to the
- whole formula), a code block quotes as a fence whose delimiter outgrows any
- backtick run inside it, a table quotes as one `a | b` line per row, and both
- Quote paths — row action and floating affordance — share that one recovery.
-- **Add to chat** opens the annotation comment editor instead of quoting when
- the row is an assistant turn (§11.10, D-LOCAL-response-annotations): the excerpt is snapshotted into
- the editor before the selection collapses, and the attachment is created when
- the editor saves — the editor itself sends nothing. The assistant turn's
- action row does the same for its selection (or the whole answer when there is
- no selection). Quoting into the draft remains the path for a user message and
- for the side chat's **Add to main chat**.
-
---
## 9. ToolCallRow
@@ -2521,11 +2395,11 @@ reasoning-level control.
| State | Appearance | Actions |
|---|---|---|
| Idle (no model) | textarea active, send button disabled + tooltip "Configure a model first" | Agent link remains available in model menu |
-| Idle (ready) | textarea active; Send requires draft content or saved annotations | Send active when content exists |
+| Idle (ready) | textarea active; Send requires draft content | Send active when content exists |
| Home/new-session initialization | textarea and mode/model × reasoning/permission triggers remain available while the durable empty session is loading; the session row is already present and the first configuration selection applies to that session | Configure the session, then send |
| New session (reasoning model) | Combined model × reasoning chip shows the model and its binding default thinking level | User may select any level enabled in the model binding, including Off when enabled |
| New session / switch while another session is running | textarea active, send button enabled for the destination session's own run state | Send active, Stop hidden unless the destination session itself is running with an empty draft |
-| Running | textarea and mode/model × reasoning/permission controls remain editable for the next turn; the single submit slot shows Stop only with an empty draft and no saved annotations | Send queues text, attachments, or saved annotations alone; Stop when all are empty |
+| Running | textarea and mode/model × reasoning/permission controls remain editable for the next turn; the single submit slot shows Stop only with an empty draft | Send queues text or attachments; Stop when both are empty |
| Context checkpoint | Same as Running until durable checkpoint completion; intermediate `turn_end` does not reactivate controls. A retained-tail fallback remains Running and shows a warning toast | Same single-slot Stop/Send behavior as Running |
| Permission pending | textarea disabled (per [03-permission-ux.md](03-permission-ux.md) §7) | Send disabled; Stop remains active whenever the running empty-draft condition is met |
| Plan / Goal / planning | textarea active while idle; contract badge and permission chip visible; mode chip pulses while the live turn projects `planning` | inspect, send, or submit a contract |
@@ -2570,12 +2444,11 @@ reasoning-level control.
timer, and clearing or sending a draft never changes the guidance.
- Escape: when textarea focused, clears input or blurs (not abort)
- Send while running: clears the current draft and appends one FIFO row to the
- active session's Host-owned queue when the draft has content or saved
- annotations. The row is sent as a new normal prompt only after the current run
- reaches `agent_end`; a different session's queue is not affected by switching
- sessions. Running with an empty draft and no saved annotations changes this
- same submit slot to Stop. Clear both draft and annotations to expose the
- immediate-stop action.
+ active session's Host-owned queue when the draft has content. The row is sent
+ as a new normal prompt only after the current run reaches `agent_end`; a
+ different session's queue is not affected by switching sessions. Running with
+ an empty draft changes this same submit slot to Stop. Clear the draft to
+ expose the immediate-stop action.
- Queued row: the text, then move up, move down, Send now, edit, and remove.
Move up/down swaps the row with its adjacent waiting neighbour and mirrors the
Host's durable `position`; at the waiting-block boundary it is a no-op and
@@ -2594,8 +2467,7 @@ reasoning-level control.
as already decided (`chat.sendNowPending`). The row carries a distinct
promoted surface so it is not mistaken for another waiting row.
- Stop: the single submit slot is shown only while a turn is running and the
- draft is empty and there are no saved annotations. It stops the running turn
- and cancels pending permission.
+ draft is empty. It stops the running turn and cancels pending permission.
Before any
assistant text, thinking, or tool row begins, it also removes the just-sent
user row and restores the pre-serialization composer draft. Ordinary text
@@ -2766,7 +2638,7 @@ reasoning-level control.
There are no visual previews in MVP.
- No voice input
-### 11.8 Slash commands, @ file references, and clipboard files (D123–D125, D197, D209, D262, D362, D-LOCAL-message-quotes, D397, ADR 0024, ADR 0059, ADR 0070, ADR 0131, ADR 0221, ADR 0222)
+### 11.8 Slash commands, @ file references, and clipboard files (D123–D125, D197, D209, D262, D362, D397, ADR 0024, ADR 0059, ADR 0070, ADR 0131, ADR 0221, ADR 0222)
The composer owns an inline autocomplete menu — one component serving two
modes. Focus never leaves the textarea (D125).
@@ -2895,111 +2767,6 @@ Anatomy:
matches renders the localized empty row and the menu counts as closed for
key handling.
-### 11.9 Quoted message drafts (D-LOCAL-message-quotes, D-LOCAL-selection-overlay)
-
-- Quote in the transcript action row (§8.8), Add to chat in the floating
- selection overlay (§8.8), and Add to main chat in the side chat (§5.8) prefill
- the composer draft with ordinary Markdown text: each
- excerpt line prefixed with `> `, then one blank line, then the attribution
- line rendered from `chat.quoteSource` ("Quoted from {{title}}"; Chinese
- "引用自 {{title}}"), where the title is the source session's title.
-- A selection is serialized back to Markdown before it becomes an excerpt
- (D-LOCAL-selection-overlay): `$…$` / `$$…$$` TeX from the KaTeX annotation, fenced code with a
- language and a delimiter that outgrows its content, backticked inline code,
- one `a | b` line per table row, `[x] `/`[ ] ` for task checkboxes, and no
- transcript chrome. Excerpt whitespace is collapsed to source-like text, so a
- rendered block boundary never becomes a stray blank line.
-
----
-
-## 11.10 Response annotations (D-LOCAL-response-annotations)
-
-- Selecting text inside an assistant turn and activating **Add to chat** — or the
- turn's annotate action — opens a compact comment editor over the conversation
- instead of attaching the excerpt immediately. The editor shows the excerpt
- snapshot (the Markdown serialized when the selection was taken, before focus
- moves into the editor and collapses the selection) above a multiline, optional
- comment. **Save** attaches the annotation with the comment in its `annotation`
- field. In the comment textarea, **Enter** saves the live value and **Shift+Enter**
- inserts a newline, independent of the main composer's Enter-to-send preference.
- IME confirmation Enter never saves; key-repeat is ignored by the editor. Saving
- by keyboard only attaches/updates the annotation, never sends a prompt.
- **Cancel**, **Escape** outside IME composition, and a press starting on
- the backdrop discard it. Dragging a selection out of the editor never dismisses
- it. The dialog owns Escape before application shortcuts and restores focus to
- its trigger, or the rich composer when the floating trigger is gone. Opening
- or saving the editor never sends. The answer body is not decorated: an
- annotation appears in the answer only where the model cites it, as a small
- accent-colored numbered reference (`:codex-annotation{index="N"}` in the
- answer's source) whose tooltip is the excerpt and any comment. A marker takes
- no part in a selection, quote, or copy.
-- Re-annotating an excerpt that is already attached reopens that annotation's
- editor with its stored comment instead of adding a second attachment, so
- editing keeps the annotation's id, position, and excerpt and changes only
- `annotation`. The editor belongs to the session it was opened in: a session
- switch closes it, a save for an annotation that was already sent or removed
- changes nothing, and a save for a duplicate excerpt is a no-op.
-- ADR floating-annotation-index replaces the composer popover with a floating index above the composer
- in the visible writable transcript. Its count header expands/collapses the list
- without deleting annotations. Each numbered excerpt/comment has locate, edit,
- and remove controls; clear-all remains available. Controls include the ordinal
- in accessible names. No attachment text enters the editable draft.
-- All saved, resolvable selections remain highlighted whenever visible, including
- before any locate click and while the floating index is collapsed. Selecting one
- item never hides the other highlights. Removal/clear/send clears the corresponding
- highlights; unresolved row fallbacks do not highlight an entire answer.
-- Matching numbered source badges sit outside the answer DOM and follow scroll,
- resize, and content layout. Clicking a badge or list entry releases follow mode,
- reveals the source (expanding/loading history if necessary), and highlights the
- selected range without changing Markdown or selection. Unresolvable ranges
- explicitly fall back to the source row, not a guessed repeated phrase. Crowded
- badges stack within the visible band; all items remain available in the index.
-- Renderer-only text offsets distinguish repeated occurrences. Deduplication uses
- source row, excerpt, and offsets; the same phrase elsewhere gets its own number.
- If either entry lacks offsets, the same row/excerpt reopens the existing item
- rather than assuming another occurrence. History reveal grows by at most 40 rows
- per frame. Anchors never enter the prompt payload. Hidden/read-only panes show no overlay.
- Array order remains the numbering for list, badges, and next-send payload.
-- Saved annotations alone enable Send (or queue while running), even when the
- composer is empty/whitespace-only. Click and Enter share the same live-state
- check. Unsaved comments and annotations in another session do not count; an
- entirely empty submission stays disabled. Model/paste/approval gates remain.
- No filler request is inserted: `## My request:` may have an empty body, and the
- existing annotation instruction tells the model to address each comment.
- Host trimming of that empty body must not expose the internal block on display.
-- A send while annotations exist composes the prompt the model receives as the
- block `# Response annotations:` + the instruction sentence +
- `<response-annotations>` with `[{"text", "annotation", "source": {"messageId"}}]`
- in numbering order + `## My request:` + the user's text, and consumes the
- annotations. Numbering is the attachment order, so "annotation 2" always names
- the second chip in the list.
-- Send and queue snapshot annotations for their originating session. Only a host
- acknowledgement consumes the submitted, unchanged annotations; new items and
- comments edited while awaiting acknowledgement remain pending. A rejected send
- retains annotations and restores the submitted draft only if no newer draft
- occupies its session slot. Queue acknowledgement is exposed as the internal
- renderer action `enqueuePrompt: Promise<boolean>`; the host protocol is unchanged.
- A per-session submission guard rejects repeat submissions while acknowledgement
- is pending, without consuming attachments. Other sessions and steering remain
- independent; the guard is released on success/failure, not at turn completion.
-- Active-turn steering (the upstream **Alt+Enter** shortcut or steer button) sends
- text only and leaves annotations pending for the next ordinary send/queue.
- Annotation-only steering is a no-op. **Shift+Enter** remains a newline in the
- main composer and in the comment editor; the editor's **Enter** only saves,
- and IME confirmation never saves or submits.
-- Queue previews and a stored user message's edit seed show only the request,
- including ordinary Markdown headings. Editing regenerates from those edited
- words; it does not reconstruct already-consumed annotation attachments. Retry
- without editing still uses the stored prompt, including its original block.
-- Nothing the user sees carries the block: the draft, the optimistic row, the
- sidebar title, and the composer's edit seed keep the user's own text, and a
- stored prompt that carries the block is displayed through its request text
- only.
-- The excerpt is capped at 2000 characters with a trailing ellipsis, and the
- editor's excerpt snapshot is the same excerpt the annotation carries. Quoting
- inserts the draft and focuses the composer; it never sends, never creates a
- session, and adds no chip kind and no file reference.
-
---
## 12. Model selection
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 128fa86c2..e17ec4fbc 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -475,21 +475,6 @@ may be retained while exactly one workspace supplies the visible shell context.
switching back restores it; selecting a workspace without an active
conversation hides the panel. Session/workspace identity remains attached to
every relative resource, preventing cross-context reinterpretation.
-- A side chat (D-LOCAL-message-quotes) is one more resource in the same context: the message
- action opens a renderer draft in the origin session's retained context.
- First Send forks through `session.fork` without activating the child and
- replaces the draft tab with `sidechat:<childSessionId>`.
- The tab label reuses `sideChat.title`, the body renders the child's transcript
- from the same event stream through the background-transcript reducer, and the
- compact input sends to and stops the child session, never the visible one.
-- Closing the `sidechat` tab, opening the child as a conversation, or deleting
- the parent or child session removes the registration; the child stays an
- ordinary session in the sidebar, lists, and search. Like every other resource
- it does not survive relaunch, while the durable child session does.
-- Closing the final side-chat tab keeps the upstream panel launcher visible.
- Closing it beside other tabs leaves those resources and other sessions intact.
- Registered transcripts and side-chat drafts survive tab switches. Scroll
- position belongs to the mounted tab and may reset on remount.
- Relaunch discards every session context, including Browser resources; only
the committed preferred panel width persists. Native window state is stored
independently from normal bounds, including when the app closes while
@@ -990,77 +975,9 @@ Running turns and pending approvals continue to gate the controls.
remain text-selectable for inspection and copying.
- Interactive controls nested inside selectable content remain
non-selectable and must keep their click and keyboard behavior.
-- A non-empty selection inside a transcript row raises one floating overlay
- above it (D-LOCAL-selection-overlay): Add to chat, Ask in side chat, and Copy. It is centered on the
- selection, clamped into the clipping ancestors' rects (capped above the docked
- composer), portaled above the transcript, and it follows the selection while
- the thread scrolls instead of disappearing. It recomputes on selection change,
- double click, key up, pointer up, pointer cancel, and resize, and hides when a
- press lands outside it, when the selection collapses, and after any action
- (each action clears the native selection). A selection that spans two rows
- raises no overlay, and a range that leaves its row is clamped back to it. It
- never renders in a read-only projection, and it does not steal the selection:
- the pointer press is prevented so the excerpt is whatever was selected,
- including a whole formula. Add to chat writes a composer draft and focuses the
- composer; Ask in side chat prefills a blockquote in the side chat anchored at that
- row; neither sends into the conversation being read. On an assistant turn, Add
- to chat opens the annotation comment editor instead of writing draft text
- (D-LOCAL-response-annotations): the editor snapshots the excerpt, Save attaches one annotation to the
- session's floating index, and the next send carries the excerpts as numbered prompt
- data (see §7.5a).
- Selection rules must not disable `focus-visible` feedback or native window
drag regions.
-### 7.5a Annotations
-
-- An annotation belongs to an **assistant turn**, never to the user's own
- message: annotating is a response concept (D-LOCAL-response-annotations). Selecting text inside a
- response, or activating the turn's annotate action, opens a compact comment
- editor on a snapshot of the excerpt; **Save** attaches one numbered annotation
- with the optional comment; **Enter** in the comment textarea does the same,
- while **Shift+Enter** keeps native multiline input and IME confirmation Enter
- never saves. **Cancel** and **Escape** discard it. Saving
- the editor sends nothing, and an excerpt that is already attached reopens its
- own annotation for editing instead of adding a second one (same row and selected
- offsets; repeated phrases elsewhere remain separate under ADR floating-annotation-index). The annotation does
- not edit the response: the answer gains a numbered reference only where the
- model cites the annotation (`:codex-annotation{index="N"}`), and that reference
- is a tooltip target, not selectable text.
-- Annotations are session state that lives exactly as long as the send that
- carries them. They are numbered in attachment order, listed in a collapsible
- floating index above the composer with matching out-of-flow source badges
- (ADR floating-annotation-index). Locate releases follow mode and reveals/highlights the source;
- edit opens the existing comment editor. All saved exact ranges stay highlighted
- without selecting an item; collapsing or selecting another item retains every
- highlight. Remove/clear/send removes them with their annotations, and unresolved
- ranges never shade the whole answer. All are consumed
- by the send. They are not persisted and do not survive
- relaunch. The editor is owned by the session it was opened in: a session switch
- closes it, and a save for an annotation that was already sent or removed is
- dropped.
-- Saved annotations make an empty composer sendable: click Send or press Enter
- to send only the annotations, or queue them while a turn runs. Unconfigured
- models, pending approval, and unfinished paste still block sending. Unsaved
- comments and other sessions' annotations do not enable Send; clearing the last
- annotation restores the empty-draft disabled/Stop behavior. No request text is
- fabricated, and a rejected send keeps the annotations.
-- A send with annotations attaches them to the prompt as numbered data before the
- user's own request, so the model can address `Annotation 1`, `Annotation 2`, …
- The user's prompt text stays what the user typed: no excerpt is copied into the
- draft, the optimistic row, or the session title.
-- Because the stored prompt carries the block, every read surface shows the
- request only: the transcript's user row, the composer's edit seed, and the
- minimap all reduce a stored prompt to its request text.
-
-- Host acknowledgement, not an optimistic queue row, consumes annotations. The
- originating session retains any attachments added or edited during the wait;
- host rejection or an unexpected pre-host exception leaves them pending, returns
- a rejected submission, and does not overwrite a newer composer draft.
-- **Alt+Enter**/steer sends only text and leaves pending annotations untouched;
- no text means no steering turn. **Shift+Enter** inserts a newline. The comment
- editor owns its own **Enter** (save only), **Shift+Enter** (newline), and IME
- confirmation, independently of the main composer's shortcuts.
-
## 8. Drag / drop
### 8.1 MVP status
@@ -1549,11 +1466,3 @@ This does not prevent state changes — it makes them instant.
the expanded sidebar yields at the threshold and returns when the panel
closes, and divider cancellation restores the prior panel width
(ADR 0033 / ADR 0151 / ADR 0238)
-
-### Side-chat draft lifecycle (Issue #421)
-
-Open side chat and selection Ask in side chat create a renderer-only draft.
-Selection text is prefilled as a blockquote, without sending. First nonempty
-Send creates the anchored child and sends once; failure keeps the draft and
-reuses any already-created child. Closing before Send creates no history.
-Existing child sessions remain after close.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 5d7e64861..8ed0dca15 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -1330,7 +1330,7 @@ identify the platform validation still needed.
refused with a visible message and the row stays queued. With an empty input
the row leaves the queue, the Host no longer lists it, and the composer holds
the exact text plus the original file-reference chip — not the
- annotation-stripped inline content. Re-sending produces the same prompt as the
+ serialized prompt the Host received. Re-sending produces the same prompt as the
queued row would have.
- **Specs linked**: `04-ux/08-component-spec.md` (§11), ADR 0265
- **Acceptance**: C (chat, stream)
@@ -1359,269 +1359,6 @@ identify the platform validation still needed.
- **Status**: Source-level regression covered (`session-create.test.mjs`,
`session-switch-performance.test.mjs`); full UI scenario Draft
-#### E2E-CHAT-quote-prefill: Quoting a message or a selection prefills the composer without sending
-
-- **Preconditions**: A session with at least one user message and one completed
- assistant answer; a second configured session exists; no turn is running.
-- **Steps**: 1) Hover the user message and activate Quote. 2) Inspect the
- composer draft, the transcript, and the sidebar. 3) Select a phrase inside the
- assistant answer and activate Add to chat (`chat.addToChat`) in the overlay
- that floats above the selection: on an assistant turn this opens the comment
- editor instead of editing the draft (E2E-CHAT-annotation-attachments), so cancel it with Escape, then
- select a phrase inside the user message and quote it through that message's
- row Quote action. 4) Send the
- quoted draft. 5) Repeat step 1 for an excerpt longer than 2000 characters,
- stop the unanswered send, and switch sessions and back.
-- **Expected**: The draft gains `> ` on every excerpt line, one blank line, then
- the localized attribution rendered from `chat.quoteSource`
- ("Quoted from {{title}}" / "引用自 {{title}}") naming the source session's
- title; step 3's cancelled editor adds no annotation and no draft text, and the
- Quote action inserts only the live selection. No turn starts, no transcript row is
- added, no session is created, and focus moves to the composer. The excerpt is
- capped at 2000 characters with a trailing ellipsis, and no reference chip
- appears. The send transmits ordinary prompt text, smart Stop restores the
- quoted draft after the unanswered send, and the draft slot survives the
- session switch. Step 3 shows exactly one overlay, centered above the
- selection, clamped inside the transcript's bounds and above the composer band,
- offering Add to chat, Ask in side chat, and Copy. It follows the selection when
- the thread scrolls, hides on a press outside it, on selection collapse, and
- after the action consumes the selection, and it is absent from the read-only
- side-chat projection of the same message.
-- **Specs linked**: `04-ux/08-component-spec.md` §8.8, §11.9;
- `04-ux/09-interaction-patterns.md` §7.5, §8a.2; ADR message-quotes-and-side-chats, D-LOCAL-message-quotes, D-LOCAL-selection-overlay
-- **Acceptance**: C (conversation), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-side-chat-fork: First Send creates the child without switching the visible session
-
-- **Preconditions**: A session with completed messages and a configured provider.
-- **Steps**: 1) Open a side chat twice from the same message. 2) Type but do
- not send; inspect persistent sessions. 3) Close it and inspect again.
- 4) Reopen and Send nonempty text twice concurrently. 5) Repeat with fork
- failure and prompt rejection; retry. 6) Switch parent or close during creation.
-- **Expected**: Open/type/close create zero sessions. First Send creates one
- anchored child and submits once. The main conversation stays selected.
- Failure keeps the draft and retries reuse any created child. A changed draft
- is never overwritten. The original parent's retained tab is replaced in place;
- closing during creation never resurrects it. Promotion is disabled for drafts.
-- **Specs linked**: `04-ux/08-component-spec.md` §5.8, §8.8;
- `04-ux/09-interaction-patterns.md` §1.8; `03-runtime/04-data-storage.md`;
- ADR message-quotes-and-side-chats, ADR 0023, D-LOCAL-message-quotes
-- **Acceptance**: C (conversation), F (persistence), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-side-chat-stream: The side-chat panel streams the child's turn live
-
-- **Preconditions**: A registered side chat whose child session has no turns
- yet; permission mode Ask so one tool call is gated.
-- **Steps**: 1) Enter a prompt in the side-chat input and Send. 2) Watch the
- panel while the child streams thinking, a tool call, and the answer. 3) Answer
- the child's permission card from the panel, then answer its ask card when the
- child asks a question. 4) Send a prompt that calls a gated tool and press Stop
- while the child is answering.
- gated tool and press Stop while the child is answering.
-- **Expected**: The panel renders the child's transcript with the existing
- transcript components and updates on the same message/tool
- start-update-end events the active transcript consumes, although the child is
- never the active session; send and Stop target the child through the existing
- prompt and abort paths and the main conversation gains no row. The permission
- card and the ask card each resolve by their own request's session id, so a
- child that needs approval or an answer never stalls behind an invisible prompt.
- side-chat title, Add to main chat (`sideChat.addToMain`), Open as a
- conversation (`sideChat.openAsSession`), and the shared close control; the
- input uses `sideChat.placeholder` and `sideChat.empty`, Send reuses
- `chat.send`, and Stop reuses `chat.stopGenerating`.
-- **Specs linked**: `04-ux/08-component-spec.md` §5.8, §11.2;
- `03-runtime/10-session-state-machine.md`; ADR message-quotes-and-side-chats, ADR 0023
-- **Acceptance**: C (conversation), E (permissions), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-side-chat-add-to-main: Add to main chat prefills the main composer with the newest answer
-
-- **Preconditions**: A registered side chat whose child has at least one
- completed assistant answer and whose panel is visible; the main composer is
- empty.
-- **Steps**: 1) Activate Add to main chat (`sideChat.addToMain`) in the
- side-chat header. 2) Inspect the main composer, the main transcript, and the
- side-chat panel. 3) Send the draft. 4) Repeat for an answer longer than 2000
- characters.
-- **Expected**: The main conversation's composer receives a Markdown blockquote
- of the side chat's newest assistant answer under the same contract as message
- quoting — `> ` on every line, one blank line, then the attribution naming the
- side-chat title — capped at 2000 characters with a trailing ellipsis. Nothing
- is sent automatically, no transcript row appears before the user sends, the
- side chat keeps its registration and tab, and no reference chip is added.
-- **Specs linked**: `04-ux/08-component-spec.md` §5.8, §11.9; ADR message-quotes-and-side-chats, D-LOCAL-message-quotes
-- **Acceptance**: C (conversation), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-side-chat-promote: Open as a conversation activates the child and releases the panel entry
-
-- **Preconditions**: A registered side chat with streamed content and a
- retained main-conversation panel context.
-- **Steps**: 1) Activate Open as a conversation (`sideChat.openAsSession`).
- 2) Inspect the active session, the sidebar selection, the composer, the
- transcript, and the panel's context menu. 3) Send a follow-up prompt in the
- activated child, then switch back to the main conversation.
-- **Expected**: The child becomes the visible session through the normal
- session-selection path with its full durable transcript, composer, prompt
- queue, and Stop controls. The side-chat registration and its `sidechat` tab
- are released, so the panel no longer lists that resource, while the main
- conversation's transcript and retained panel context are unchanged.
-- **Specs linked**: `04-ux/08-component-spec.md` §5.8;
- `04-ux/09-interaction-patterns.md` §1.8; ADR message-quotes-and-side-chats, ADR 0023, D128
-- **Acceptance**: C (conversation), F (persistence), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-side-chat-close: Closing the side-chat tab keeps the child session
-
-- **Preconditions**: A registered side chat whose tab is open and whose child
- already appears in the sidebar; a second parent session for the deletion pass.
-- **Steps**: 1) Close the `sidechat` tab from its menu row or the header close
- control. 2) Inspect the panel and the sidebar. 3) Search for the child, open
- it, then restart the app and look for it again. 4) Register a fresh side chat,
- delete its parent session, then repeat and delete the child session.
-- **Expected**: Closing the tab removes the registration and its transcript
- projection and nothing streams into the panel afterwards, while the child
- session is not deleted and stays in the sidebar, session lists, and search as
- an ordinary conversation. After a restart the child session is still present
- and no `sidechat` tab or projection is restored. Deleting the parent or the
- child also removes the registration and its tab.
-- **Specs linked**: `04-ux/08-component-spec.md` §5.8;
- `03-runtime/04-data-storage.md`; ADR message-quotes-and-side-chats, ADR 0023, D128
-- **Acceptance**: C (conversation), F (persistence), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-selection-markdown: Quoting a formula, a table, and a code block recovers Markdown
-
-- **Preconditions**: A session with a completed assistant answer containing an
- inline formula, a display formula, a GFM table, a fenced code block, a file
- reference rendered as inline code, and a task list; no turn running.
-- **Steps**: 1) Drag-select part of the inline formula and activate the floating
- quote affordance. 2) Select the display formula alone. 3) Select the whole
- table and a code fence in one drag. 4) Inspect the composer draft after each
- step, then select a phrase and scroll the thread, resize the window,
- double-click a word, drag a selection across two messages, collapse the
- selection, and open the same message in a side-chat projection.
-- **Expected**: Each draft carries the rendered text as Markdown: `$…$` TeX for
- an inline formula and `$$…$$` for a display formula, never KaTeX's duplicated
- MathML/HTML text; one `a | b` line per table row; a fenced block whose
- delimiter outgrows any backtick run inside the snippet and keeps its language;
- backticked inline code whose file-reference chip keeps its code text; and
- `[x] `/`[ ] ` for a task list. Chrome (hover action rows, copy buttons, the
- checkbox control) never appears in the excerpt. Each quote is one `> `-prefixed
- blockquote plus the `chat.quoteSource` attribution, appended after any existing
- draft, capped at 2000 characters, with no chip added and no turn started. The
- overlay is the only one on screen, sits centered above the selection inside the
- transcript bounds and above the composer band, follows the thread scroll rather
- than disappearing, hides on a press outside it and on selection collapse, is
- absent from a read-only side-chat projection, and never appears for a drag that
- crosses two messages — such a range is clamped back to its own row instead.
-- **Specs linked**: `04-ux/08-component-spec.md` §8.8, §11.9;
- `04-ux/09-interaction-patterns.md` §7.5; ADR message-quotes-and-side-chats, D-LOCAL-selection-overlay
-- **Acceptance**: C (conversation), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-selection-side-chat: Selection prefills a side-chat draft
-
-- **Preconditions**: A session with a completed answer; no turn running.
-- **Steps**: 1) Select a phrase and choose Ask in side chat. 2) Inspect the
- panel input, persistent session count, and model request count. 3) Add a
- question and explicitly Send.
-- **Expected**: The selection is a Markdown blockquote in the side input.
- Opening creates no child and sends no model request. Explicit Send creates
- one child and sends the edited draft. The main draft and transcript remain
- unchanged; selecting another quote appends without erasing existing text.
-- **Specs linked**: `04-ux/08-component-spec.md` §5.8, §8.8; ADR message-quotes-and-side-chats, D-LOCAL-message-quotes,
- D-LOCAL-selection-overlay
-- **Acceptance**: C (conversation), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-annotation-attachments: Annotating a response attaches numbered prompt data, not draft text
-
-- **Preconditions**: A session with a completed answer containing at least two
- distinct paragraphs; no turn running.
-- **Steps**: 1) Select a phrase in the first paragraph and activate Add to chat
- in the floating overlay; the comment editor opens with that excerpt — type a
- comment and Save. 2) Select a phrase in the second paragraph, add it with an
- empty comment, then select the first phrase again, edit its comment, and Save.
- 3) Inspect the answer, the composer, and the editor draft; expand the floating
- annotation index and inspect the list. 4) Send an instruction and inspect the request
- the agent received.
-- **Expected**: Activating Add to chat opens the editor and sends nothing: no
- turn starts, no draft text appears, and Save attaches the annotation with the
- comment in its `annotation` field while Escape and Cancel attach nothing. The
- editor shows the selected Markdown as its excerpt snapshot. The answer body is
- unchanged: nothing is inserted into its Markdown. Independent source badges
- show the same numbers as the floating index (ADR floating-annotation-index / E2E-CHAT-annotation-source-index).
- The index lists `1. <excerpt>` and `2. <excerpt>`; step 2 leaves two entries (reopening the
- first excerpt edits annotation 1's comment instead of adding a third), and the
- attachment's list shows each excerpt with its comment and its own edit and
- remove controls beside the clear-all control. Where the model cites an
- annotation, that citation
- renders as a small numbered reference whose tooltip is the excerpt, and no
- marker joins a selection, a quote, or a copy of the answer. The draft text, the optimistic user row, the
- sidebar title, and the composer's edit seed contain the user's own words only —
- no excerpt, no blockquote, no attribution line. The request the agent receives
- begins with `# Response annotations:` and the instruction sentence, carries
- `<response-annotations>` with
- `[{"text","annotation","source":{"messageId"}}]` in that order — annotation 1
- with the edited comment, annotation 2 with an empty comment — and continues
- under `## My request:` with the typed instruction. The attachment is gone after
- the send, and the transcript shows the stored prompt as the typed instruction
- only.
-- **Specs linked**: `04-ux/08-component-spec.md` §8.8, §11.10;
- `04-ux/09-interaction-patterns.md` §7.5a; ADR response-annotations, D-LOCAL-response-annotations
-- **Acceptance**: C (conversation), Quality
-- **Milestone**: M6+
-- **Status**: Draft
-
-#### E2E-CHAT-annotation-session-state: Annotation state is session-scoped and never persisted
-
-- **Preconditions**: Two sessions; a completed answer in the first; no turn
- running.
-- **Steps**: 1) Annotate one pass in the first session and save a comment, then
- open the editor again and press Escape. 2) Switch to the second
- session and inspect the transcript. 3) Switch back and expand the floating
- annotation index. Verify per-item controls announce their annotation numbers.
- 4) Edit the comment from the list and remove one item from it;
- annotate again, clear the annotations from
- the floating index, and send a prompt. 5) Annotate again and restart the
- app. 6) Open a new annotation editor, type with a CJK IME, and press Escape
- while composing. Drag-select comment text and release outside the dialog.
- Finish composing, then press Escape normally and inspect focus and run state.
- 7) Reopen the editor, type a comment with Shift+Enter between lines, and press
- Enter to save. Repeat with the main composer's Enter-to-send preference disabled
- and with an IME candidate-confirmation Enter.
-- **Expected**: Step 7 saves the multiline comment on plain Enter without sending
- a prompt; Shift+Enter inserts a newline. IME confirmation keeps the editor open,
- and the main composer's preference does not change these editor shortcuts.
- Step 6 keeps the editor and typed text during IME Escape and
- drag-selection overshoot. Normal Escape closes only the editor (never aborts
- the run) and restores focus to its trigger or the rich composer. The attachment
- belongs to the session it was made in: the second
- session shows none, and switching back restores it unchanged. The cancelled
- editor adds nothing, the list edits that annotation's comment in place, and
- removing an item drops just that annotation while clear-all drops every
- remaining one; the following send carries no block. After a restart no
- annotation, marker, or attachment is restored, and the sessions are otherwise
- unchanged — annotations never reach the host on their own, no session file
- gains them, and no protocol, schema, or permission surface changes,
- including the comment editor.
-- **Specs linked**: `04-ux/08-component-spec.md` §11.10;
- `04-ux/09-interaction-patterns.md` §7.5a; `03-runtime/04-data-storage.md`;
- ADR response-annotations, D-LOCAL-response-annotations
-- **Acceptance**: C (conversation), F (persistence), Quality
-- **Milestone**: M6+
-- **Status**: Draft
### Conversation Top Bar
@@ -5967,8 +5704,6 @@ identify the platform validation still needed.
`apps/desktop/test/rpc-lifecycle-contract.test.mjs` (client precheck),
`packages/shared/src/rpc-limits.test.ts`. Desktop journey remains Draft.
-
-
#### E2E-119: Parallel subagents report back without entering the parent's context
- **Preconditions**: A project-bound Agent session with the user home containing
@@ -7462,76 +7197,6 @@ identify the platform validation still needed.
Responses and its original alias, while the copy retained Anthropic Messages
and its edited alias. Credential-bearing network discovery, external-model
calls, and the OpenCode Go UI variant were not exercised.
-### E2E-CHAT-annotation-source-index: Floating annotation index and numbered source locations
-
-- **Status**: Draft (not run)
-- **Preconditions**: A long session with repeated phrases, a formula, and a code block;
- another retained session; a writable main transcript and read-only side chat.
-- **Steps**: 1) Annotate two occurrences of identical words and add comments.
- 2) Inspect both saved ranges before clicking any item, then collapse and expand
- the floating index. 3) Click each numbered item, then
- its source badge. 4) Scroll, resize the work panel and composer, and revisit the
- session after its source is outside the mounted history window. 5) Edit/remove
- an item; clear or send the remaining annotations. Copy the answer and inspect
- the outgoing prompt. 6) Repeat on formulas, split highlighted code, and a source
- whose text changed or was removed. 7) Save an annotation, empty the composer,
- and send using the button; repeat with Enter and while running. Try whitespace
- only, no saved annotations, another session's annotations, and a blocked send.
-- **Expected**: One floating index stays above the composer. Collapse retains a
- small count header and visible source badges. Both saved exact ranges stay
- highlighted before any click, while collapsed, and when another item is selected;
- deleting one removes only its highlight, clear/send removes all. Unresolved
- ranges never highlight the whole answer. List and badge numbers agree with
- prompt array order, renumbering after removal. Distinct occurrences remain
- separate; repeating one selection edits that annotation. Locate releases follow
- mode, loads/mounts history if needed, scrolls the same pane and overlays a highlight
- on the exact range. Ambiguous/stale ranges fall back to the source response with
- an explicit tooltip; absent rows never jump to another answer. Badges stack when
- coincident and clip to the visible transcript, never the composer. Copied answer
- text, Markdown, formulas and layout are unchanged. Anchor metadata is not in the
- prompt. Hidden/read-only panes show no index or badges. Send/clear removes both;
- no persistence, host protocol, schema, IPC or permission change. Step 7 enables
- Send for saved annotations without request text (queues while running), carries
- each excerpt/comment in the existing block, and consumes only that session's
- sent annotations. No filler request is invented. Truly empty submissions remain
- disabled; model/paste/approval blocks and rejection retain annotations. Trimmed
- annotation-only prompts never display the internal block.
-- **Specs linked**: `04-ux/08-component-spec.md` §11.10;
- `04-ux/09-interaction-patterns.md` §7.5a; ADR floating-annotation-index (amends D-LOCAL-response-annotations).
-- **Acceptance**: C (conversation), Quality
-- **Milestone**: M6+
-
-### E2E-CHAT-annotation-ack-and-steering: Preserve annotation ownership across upstream send paths
-
-- **Preconditions**: An isolated fixture profile has two sessions, saved annotations,
- a controllable prompt/queue acknowledgement, and an active turn for steering.
-- **Steps**: Submit annotations with and without request text; delay acknowledgement,
- press Enter again (no duplicate), add another annotation, edit a submitted
- comment, and switch sessions. Resolve
- success, then repeat with host rejection, an unexpected pre-host exception,
- and new draft text typed during the wait.
- Send a text-only Alt+Enter steer and try annotation-only steering. In the comment
- editor, confirm an IME candidate, save with Enter, and insert a Shift+Enter newline.
- Inspect queue previews and edit seeds for annotation-only prompts and a request
- containing an ordinary `## My request: extra` heading. Close a side-chat tab both
- as the final resource and beside another tab; inspect its durable child session.
-- **Expected**: Nothing is consumed before acknowledgement. Success consumes only
- unchanged submitted annotations in the original session; host rejection or an
- unexpected setup exception returns a rejected submission, retains annotations,
- and restores a draft only into an unchanged/empty slot. New comments, attachments,
- and another session's state survive. Steering neither carries nor consumes
- annotations; no text means no steering turn. The comment editor never triggers
- steering or send, and IME confirmation never saves. Visible projections hide only
- the generated block and preserve request headings; wire/storage remain intact.
- Closing a side-chat tab releases its projection, keeps other resources/children,
- and leaves the launcher visible when it was the final tab.
-- **Specs linked**: `04-ux/08-component-spec.md` §11.10,
- `04-ux/09-interaction-patterns.md` §7.5a; ADR response-annotations,
- ADR message-quotes-and-side-chats.
-- **Acceptance**: C (conversation), F (persistence), Quality
-- **Milestone**: M6+
-- **Status**: Unit/integration covered by `upstream-sync-annotations.test.mjs` and
- `annotation-only-send.test.mjs`; post-main desktop journey not run in merge worktree.
#### E2E-PLUGIN-global-shortcut-owns-only-its-own-command
@@ -7640,26 +7305,22 @@ identify the platform validation still needed.
## 8. Traceability Matrix
-
-
-
-
| Acceptance | Scenarios |
|---|---|
| C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back |
| B / F / Security — Provider copy | E2E-PROVIDER-copy-config-without-credentials |
| A — App startup | E2E-001, E2E-002, E2E-003, E2E-004, E2E-067, E2E-076, E2E-079, E2E-092, E2E-097, E2E-143, E2E-150, E2E-168, E2E-204 |
| B — Model config | E2E-005, E2E-006, E2E-007, E2E-038, E2E-050, E2E-052, E2E-055, E2E-066, E2E-080, E2E-082, E2E-102c, E2E-102d, E2E-102e, E2E-151, E2E-154, E2E-163, E2E-166, E2E-172, E2E-174, E2E-197, E2E-005G, E2E-005J, E2E-199, E2E-201, E2E-202, E2E-203, E2E-205, E2E-206, E2E-209 |
-| C — Conversation & stream | E2E-008, E2E-008d, E2E-008a, E2E-009, E2E-010, E2E-011, E2E-011a, E2E-011b, E2E-011d, E2E-011e, E2E-011g, E2E-031, E2E-040, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-052, E2E-053, E2E-054, E2E-055, E2E-059, E2E-059a, E2E-060c, E2E-060d, E2E-061, E2E-061a, E2E-062, E2E-064, E2E-065, E2E-068, E2E-071, E2E-073, E2E-074, E2E-075, E2E-081, E2E-083, E2E-084, E2E-086, E2E-087, E2E-088, E2E-088b, E2E-089, E2E-090, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102g, E2E-106, E2E-109, E2E-111, E2E-114, E2E-116, E2E-117, E2E-118, E2E-119, E2E-120, E2E-121, E2E-218, E2E-219, E2E-AGENTS-001, E2E-142, E2E-144, E2E-145, E2E-146, E2E-146a, E2E-147, E2E-151, E2E-154, E2E-155, E2E-158, E2E-159, E2E-161, E2E-162, E2E-166, E2E-172, E2E-173, E2E-174, E2E-177, E2E-178, E2E-179, E2E-180, E2E-182, E2E-183, E2E-187, E2E-198, E2E-199, E2E-202, E2E-203, E2E-207, E2E-208, E2E-250, E2E-102i, E2E-PLUGIN-session-orchestrator-real-workers, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-CHAT-quote-prefill, E2E-CHAT-side-chat-fork, E2E-CHAT-side-chat-stream, E2E-CHAT-side-chat-add-to-main, E2E-CHAT-side-chat-promote, E2E-CHAT-side-chat-close, E2E-CHAT-selection-markdown, E2E-CHAT-selection-side-chat, E2E-CHAT-annotation-attachments, E2E-CHAT-annotation-session-state, E2E-CHAT-annotation-source-index, E2E-CHAT-annotation-ack-and-steering |
+| C — Conversation & stream | E2E-008, E2E-008d, E2E-008a, E2E-009, E2E-010, E2E-011, E2E-011a, E2E-011b, E2E-011d, E2E-011e, E2E-011g, E2E-031, E2E-040, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-052, E2E-053, E2E-054, E2E-055, E2E-059, E2E-059a, E2E-060c, E2E-060d, E2E-061, E2E-061a, E2E-062, E2E-064, E2E-065, E2E-068, E2E-071, E2E-073, E2E-074, E2E-075, E2E-081, E2E-083, E2E-084, E2E-086, E2E-087, E2E-088, E2E-088b, E2E-089, E2E-090, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102g, E2E-106, E2E-109, E2E-111, E2E-114, E2E-116, E2E-117, E2E-118, E2E-119, E2E-120, E2E-121, E2E-218, E2E-219, E2E-AGENTS-001, E2E-142, E2E-144, E2E-145, E2E-146, E2E-146a, E2E-147, E2E-151, E2E-154, E2E-155, E2E-158, E2E-159, E2E-161, E2E-162, E2E-166, E2E-172, E2E-173, E2E-174, E2E-177, E2E-178, E2E-179, E2E-180, E2E-182, E2E-183, E2E-187, E2E-198, E2E-199, E2E-202, E2E-203, E2E-207, E2E-208, E2E-250, E2E-102i, E2E-PLUGIN-session-orchestrator-real-workers, E2E-SUBAGENT-settlement-updates-before-parent-poll |
| D — Workspace | E2E-012, E2E-013, E2E-022B, E2E-024I, E2E-047, E2E-049, E2E-057, E2E-058, E2E-060, E2E-068, E2E-075, E2E-078, E2E-153, E2E-158, E2E-182, E2E-187, E2E-252 |
| D — Workspace (project ordering) | E2E-253 |
-| E — Tools & permissions | E2E-008a, E2E-014, E2E-015, E2E-016, E2E-017, E2E-018, E2E-019, E2E-024I, E2E-024K, E2E-040, E2E-049, E2E-074, E2E-093, E2E-097, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102d, E2E-102e, E2E-102g, E2E-103, E2E-105, E2E-106, E2E-107, E2E-111, E2E-112, E2E-113, E2E-114, E2E-115, E2E-116, E2E-119, E2E-121, E2E-122, E2E-142, E2E-145, E2E-147, E2E-155, E2E-158, E2E-166, E2E-181, E2E-PLUGIN-imported-pi-package-skills, E2E-CHAT-side-chat-stream |
-| F — Persistence | E2E-020, E2E-021, E2E-021a, E2E-036, E2E-037, E2E-038, E2E-040, E2E-042, E2E-047, E2E-048, E2E-051, E2E-054, E2E-056, E2E-061, E2E-062, E2E-064, E2E-066, E2E-068, E2E-071, E2E-072, E2E-073, E2E-082, E2E-084, E2E-096, E2E-098, E2E-102, E2E-102b, E2E-102c, E2E-102d, E2E-102g, E2E-102i, E2E-103, E2E-AGENTS-001, E2E-061a, E2E-073a, E2E-104, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-118, E2E-119, E2E-120, E2E-121, E2E-123, E2E-142, E2E-146, E2E-146a, E2E-148, E2E-151, E2E-158, E2E-160, E2E-168, E2E-171, E2E-177, E2E-178, E2E-183, E2E-186, E2E-005J, E2E-PLUGIN-session-orchestrator-real-workers, E2E-CHAT-side-chat-fork, E2E-CHAT-side-chat-promote, E2E-CHAT-side-chat-close, E2E-CHAT-annotation-session-state |
+| E — Tools & permissions | E2E-008a, E2E-014, E2E-015, E2E-016, E2E-017, E2E-018, E2E-019, E2E-024I, E2E-024K, E2E-040, E2E-049, E2E-074, E2E-093, E2E-097, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102d, E2E-102e, E2E-102g, E2E-103, E2E-105, E2E-106, E2E-107, E2E-111, E2E-112, E2E-113, E2E-114, E2E-115, E2E-116, E2E-119, E2E-121, E2E-122, E2E-142, E2E-145, E2E-147, E2E-155, E2E-158, E2E-166, E2E-181, E2E-PLUGIN-imported-pi-package-skills |
+| F — Persistence | E2E-020, E2E-021, E2E-021a, E2E-036, E2E-037, E2E-038, E2E-040, E2E-042, E2E-047, E2E-048, E2E-051, E2E-054, E2E-056, E2E-061, E2E-062, E2E-064, E2E-066, E2E-068, E2E-071, E2E-072, E2E-073, E2E-082, E2E-084, E2E-096, E2E-098, E2E-102, E2E-102b, E2E-102c, E2E-102d, E2E-102g, E2E-102i, E2E-103, E2E-AGENTS-001, E2E-061a, E2E-073a, E2E-104, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-118, E2E-119, E2E-120, E2E-121, E2E-123, E2E-142, E2E-146, E2E-146a, E2E-148, E2E-151, E2E-158, E2E-160, E2E-168, E2E-171, E2E-177, E2E-178, E2E-183, E2E-186, E2E-005J, E2E-PLUGIN-session-orchestrator-real-workers |
| F — Persistence (project ordering) | E2E-251 |
| G — Plugins | E2E-022, E2E-022A, E2E-022B, E2E-022C, E2E-023, E2E-024, E2E-024B, E2E-024C, E2E-024D, E2E-024E, E2E-024W, E2E-024F, E2E-024G, E2E-024H, E2E-024I, E2E-024J, E2E-024K, E2E-024L, E2E-024M, E2E-024N, E2E-024O, E2E-024P, E2E-025, E2E-026, E2E-105, E2E-117, E2E-120, E2E-122, E2E-123, E2E-024Q, E2E-148, E2E-152, E2E-153, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-import-extension-installs-dependencies, E2E-PLUGIN-import-extension-reports-missing-dependency, E2E-PLUGIN-global-shortcut-owns-only-its-own-command, E2E-PLUGIN-permission-gate-for-real-time-capabilities, E2E-PLUGIN-background-audio-and-realtime-connection, E2E-PLUGIN-fs-root-follows-the-calling-session |
| H — Diagnostics | E2E-027, E2E-031, E2E-034, E2E-042, E2E-096, E2E-098, E2E-104, E2E-107, E2E-108, E2E-109, E2E-110, E2E-113, E2E-115, E2E-116, E2E-118, E2E-121, E2E-146, E2E-146a, E2E-155, E2E-159, E2E-176, E2E-194, E2E-195 |
| Security | E2E-028, E2E-029, E2E-030, E2E-024J, E2E-024K, E2E-024M, E2E-049, E2E-068, E2E-086, E2E-102c, E2E-102d, E2E-102e, E2E-105, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-113, E2E-115, E2E-116, E2E-117, E2E-119, E2E-121, E2E-122, E2E-123, E2E-142, E2E-148, E2E-151, E2E-153, E2E-158, E2E-187, E2E-196c, E2E-196b, E2E-196, E2E-PLUGIN-fs-root-follows-the-calling-session |
-| Quality | E2E-032, E2E-033, E2E-039, E2E-043, E2E-044, E2E-045, E2E-046, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-050, E2E-053, E2E-055, E2E-056, E2E-057, E2E-058, E2E-059, E2E-060, E2E-061, E2E-062, E2E-063, E2E-064, E2E-065, E2E-066, E2E-067, E2E-068, E2E-069, E2E-070, E2E-071, E2E-072, E2E-073, E2E-074, E2E-075, E2E-076, E2E-077, E2E-078, E2E-079, E2E-080, E2E-081, E2E-082, E2E-083, E2E-084, E2E-085, E2E-086, E2E-092, E2E-093, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102e, E2E-103, E2E-AGENTS-001, E2E-021a, E2E-024N, E2E-059a, E2E-060b, E2E-060c, E2E-061a, E2E-073a, E2E-111, E2E-114, E2E-117, E2E-118, E2E-119, E2E-120, E2E-122, E2E-123, E2E-142, E2E-143, E2E-144, E2E-145, E2E-146, E2E-147, E2E-148, E2E-150, E2E-151, E2E-153, E2E-155, E2E-158, E2E-159, E2E-160, E2E-161, E2E-162, E2E-163, E2E-168, E2E-172, E2E-173, E2E-174, E2E-011g, E2E-176, E2E-177, E2E-178, E2E-179, E2E-180, E2E-181, E2E-182, E2E-183, E2E-186, E2E-187, E2E-194, E2E-195, E2E-196a, E2E-196b, E2E-196c, E2E-198, E2E-199, E2E-200, E2E-196, E2E-201, E2E-204, E2E-202, E2E-203, E2E-205, E2E-206, E2E-207, E2E-208, E2E-209, E2E-210, E2E-218, E2E-219, E2E-250, E2E-252, E2E-102i, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-PLUGIN-imported-pi-package-skills, E2E-CHAT-quote-prefill, E2E-CHAT-side-chat-fork, E2E-CHAT-side-chat-stream, E2E-CHAT-side-chat-add-to-main, E2E-CHAT-side-chat-promote, E2E-CHAT-side-chat-close, E2E-CHAT-selection-markdown, E2E-CHAT-selection-side-chat, E2E-CHAT-annotation-attachments, E2E-CHAT-annotation-session-state, E2E-CHAT-annotation-source-index, E2E-CHAT-annotation-ack-and-steering, E2E-PLUGIN-fs-root-follows-the-calling-session |
+| Quality | E2E-032, E2E-033, E2E-039, E2E-043, E2E-044, E2E-045, E2E-046, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-050, E2E-053, E2E-055, E2E-056, E2E-057, E2E-058, E2E-059, E2E-060, E2E-061, E2E-062, E2E-063, E2E-064, E2E-065, E2E-066, E2E-067, E2E-068, E2E-069, E2E-070, E2E-071, E2E-072, E2E-073, E2E-074, E2E-075, E2E-076, E2E-077, E2E-078, E2E-079, E2E-080, E2E-081, E2E-082, E2E-083, E2E-084, E2E-085, E2E-086, E2E-092, E2E-093, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102e, E2E-103, E2E-AGENTS-001, E2E-021a, E2E-024N, E2E-059a, E2E-060b, E2E-060c, E2E-061a, E2E-073a, E2E-111, E2E-114, E2E-117, E2E-118, E2E-119, E2E-120, E2E-122, E2E-123, E2E-142, E2E-143, E2E-144, E2E-145, E2E-146, E2E-147, E2E-148, E2E-150, E2E-151, E2E-153, E2E-155, E2E-158, E2E-159, E2E-160, E2E-161, E2E-162, E2E-163, E2E-168, E2E-172, E2E-173, E2E-174, E2E-011g, E2E-176, E2E-177, E2E-178, E2E-179, E2E-180, E2E-181, E2E-182, E2E-183, E2E-186, E2E-187, E2E-194, E2E-195, E2E-196a, E2E-196b, E2E-196c, E2E-198, E2E-199, E2E-200, E2E-196, E2E-201, E2E-204, E2E-202, E2E-203, E2E-205, E2E-206, E2E-207, E2E-208, E2E-209, E2E-210, E2E-218, E2E-219, E2E-250, E2E-252, E2E-102i, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-fs-root-follows-the-calling-session |
| Quality (project ordering) | E2E-253 |
| C — Conversation & stream (IME slash alias) | E2E-255 |
| E — Tools & permissions (Skill residency) | E2E-254 |
@@ -7704,7 +7365,7 @@ identify the platform validation still needed.
| M2 (IME slash alias) | E2E-255 |
| M5 (Skill residency) | E2E-254 |
| M6 | E2E-104, E2E-105, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-111, E2E-112, E2E-113, E2E-114, E2E-115, E2E-116, E2E-117, E2E-118, E2E-119, E2E-120, E2E-103, E2E-172 |
-| M6+ | E2E-121, E2E-122, E2E-148, E2E-150, E2E-151, E2E-154, E2E-155, E2E-158, E2E-159, E2E-160, E2E-161, E2E-162, E2E-163, E2E-166, E2E-168, E2E-173, E2E-174, E2E-176, E2E-179, E2E-196a, E2E-196b, E2E-196c, E2E-198, E2E-199, E2E-200, E2E-202, E2E-203, E2E-205, E2E-209, E2E-210, E2E-212, E2E-213, E2E-214, E2E-215, E2E-216, E2E-217, E2E-218, E2E-219, E2E-257, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-CHAT-quote-prefill, E2E-CHAT-side-chat-fork, E2E-CHAT-side-chat-stream, E2E-CHAT-side-chat-add-to-main, E2E-CHAT-side-chat-promote, E2E-CHAT-side-chat-close, E2E-CHAT-selection-markdown, E2E-CHAT-selection-side-chat, E2E-CHAT-annotation-attachments, E2E-CHAT-annotation-session-state, E2E-CHAT-annotation-source-index, E2E-CHAT-annotation-ack-and-steering, E2E-PLUGIN-fs-root-follows-the-calling-session |
+| M6+ | E2E-121, E2E-122, E2E-148, E2E-150, E2E-151, E2E-154, E2E-155, E2E-158, E2E-159, E2E-160, E2E-161, E2E-162, E2E-163, E2E-166, E2E-168, E2E-173, E2E-174, E2E-176, E2E-179, E2E-196a, E2E-196b, E2E-196c, E2E-198, E2E-199, E2E-200, E2E-202, E2E-203, E2E-205, E2E-209, E2E-210, E2E-212, E2E-213, E2E-214, E2E-215, E2E-216, E2E-217, E2E-218, E2E-219, E2E-257, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-PLUGIN-fs-root-follows-the-calling-session |
| M6+ (Session Orchestrator) | E2E-PLUGIN-session-orchestrator-real-workers |
| M6+ (Session list responsiveness) | E2E-SESSION-list-refresh-keeps-desktop-responsive |
| M6+ (Independent session communication) | E2E-SESSION-independent-top-level-communication, E2E-SESSION-hover-card-model-and-links |
@@ -7736,7 +7397,8 @@ and E2E-200
When adding or changing a feature that affects user-visible or protocol-visible behavior:
-1. **Add a new scenario** using the template in §6. Assign the next available ID (`E2E-<N>`).
+1. **Add a new scenario** using the template in §6. Assign the next available ID
+ (`E2E-<N>`). IDs retired by ADR 0268 are never reused.
2. **Link it** to the relevant acceptance criterion (A–H) and milestone (M1–M6
or M6+ for the current product increment).
3. **Set status** to `Draft` unless an automated test already exists.
@@ -7898,8 +7560,6 @@ This test plan spec is accepted when:
- Every visible composer control changes the active session, opens its menu, or
submits/aborts the current turn.
-
-
### US-UI-19 Permanent Stage Manager bounds restore
- On macOS with Stage Manager, shrink or unfocus the PI window until width < 1040 or height < 700.
- Expect the shell to re-assert a Codex-like footprint (~1200×800, min 1040×700) and keep restoring while still collapsed (not only during the first 20s after launch).
@@ -8056,9 +7716,6 @@ This test plan spec is accepted when:
- On the light sidebar, the Sessions and Projects scoped create controls remain
icon-only with semantic hover wash; no standalone New task row is rendered.
-
-
-
### US-UI-43 Empty home plate Y + night elevated-primary
- Open empty home at ~1200×690 light theme.
- Composer plate is bottom-aligned and content-driven: an empty or one-line
@@ -8120,8 +7777,6 @@ This test plan spec is accepted when:
### US-UI-31b (superseded)
- Superseded by US-UI-31 home empty vertical stack (D111).
-
-
### US-UI-45 Composer width remains stable when the minimap appears
- Open empty home and record the composer plate width. Open a short transcript
that fits one viewport, then grow it until the left-edge conversation minimap
@@ -12502,31 +12157,6 @@ plugin-form fixtures in an isolated temporary directory at runtime.
- **Specs:** runtime §12; storage §12; security §12; ADR 0254.
- **Status:** Documented; run after integration into main.
-### E2E-SESSION-native-side-chat-fork-survives-close
-
-- **Preconditions:** A writable synthetic native v3 session with branches,
- compaction metadata, model/thinking entries, and a saved local model/auth
- binding. No Desktop provider secret is configured.
-- **Steps:** Open the session, fork a side chat from an assistant answer and
- from the first user message, send a prompt in the panel, stop one reply, close
- the panel, reload, reopen the child from the sidebar and by title search, and
- send while a native turn is running.
-- **Expected:** Each fork creates exactly one new v3 child JSONL anchored at the
- selected message (or the current branch endpoint) with the child title; later
- and sibling entries are excluded; parent bytes, leaf, and runtime are
- unchanged; no temporary file remains. The first-user child is durable before
- any reply and carries the parent's saved model/thinking when the branch saved
- none (an explicit branch value wins; no Desktop fallback). The panel streams a
- provisional assistant row that is replaced by exactly one durable SDK entry id
- and the optimistic user row reconciles to the durable entry id; closing the
- panel deletes neither the child nor its sidebar/search presence, and reopening
- it as a conversation keeps one copy of every row. A send during a running
- native turn fails visibly before the Desktop queue and keeps the draft; a
- live foreign lease refuses the fork and a branch whose transcript exceeds the
- general detail page still forks with its whole history.
-- **Specs:** IPC native routing; runtime §12; storage §12; UX side chat; ADR 0254.
-- **Status:** Documented; run after integration into main.
-
### E2E-SESSION-native-pi-incompatible-session-is-read-only
- **Preconditions:** Fixtures cover missing cwd, missing trailing newline,
@@ -12618,24 +12248,6 @@ plugin-form fixtures in an isolated temporary directory at runtime.
covered by host-core unit tests; the renderer's read-only row presentation
remains additional validation.
-### Issue #421 validation scope
-
-E2E-CHAT-side-chat-fork, E2E-CHAT-side-chat-close, and
-E2E-CHAT-selection-side-chat cover deferred creation and quote prefill.
-`pnpm test:e2e:native-side-chat` exercises renderer draft opening/closing,
-first-send native materialization and subsequent streaming/persistence.
-`side-chat-draft.test.mjs` covers deterministic failure and navigation races.
-Native E2E uses a fixture transport, not a live provider account.
-
-### E2E-CHAT-side-chat-fork availability extension (#421)
-
-Open a draft, type a question, then make the parent busy and read-only in turn.
-Expect a disabled Send button, visible reason, unchanged draft and no new host
-session or model request. Restore availability and send; exactly one child
-is created. A child returning read-only from an in-flight fork must not be
-prompted. `test:e2e:native-side-chat` covers the rendered parent gate and its
-recovery; `side-chat-draft.test.mjs` covers action-level guards and child drift.
-
#### E2E-CHAT-disclosure-toggle-keeps-reading-position
- **Scope**: Manual disclosure of a tool, thinking or activity title in a
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index fd5e1f644..4997fb0c1 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -71,8 +71,8 @@ This log freezes previously open questions into concrete decisions.
| D393 | User-invoked Skills in the composer | **Amend D123 / D174 / ADR 0024 / ADR 0039: active built-in, plugin, and user Skills appear in a separate `Skills` group at the end of the composer slash menu. Selecting one inserts its exact id; Electron main revalidates the active project scope at send time and asks the model to call the local `Skill` tool, preserving on-demand body loading and existing permissions. Existing command names win collisions; inactive Skills remain literal slash text. See ADR 0219 and E2E-088b.** | D174's model-invoked catalog remains the body-loading and security contract, while a final explicit entry makes known workflows discoverable without moving Skill bodies into the renderer, prompt, or host protocol. |
| D394 | Windows work-panel chrome keeps one resource action cluster | **Amend D154 / D357 / ADR 0195: the open work-panel header keeps one compact resource switcher; resource close is owned by the existing keyboard-operable context-menu rows, the viewport-fixed toggle remains the only panel collapse control, and subagent detail returns with a back chevron. Windows/Linux native controls remain fixed at the window edge. Renderer-only; no panel state, window geometry, IPC, protocol, or storage change. See ADR 0220 and E2E-067.** | The header resource `X`, viewport-fixed toggle, and Windows native close cluster read as duplicate close actions and became cramped at narrow panel widths. |
| D396 | Renderer and plugin-panel scrollbars share one compact contract | **Amend D300: every renderer scroll container uses one 6px, trackless, transparent-at-rest scrollbar with the same hover, focus-within, scroll-reveal, and dragged-thumb states. Remove the sidebar-specific width and opacity override. The plugin-panel preload applies the same contract and 300ms reveal mark to docked and detached plugin documents, including the bundled Files view. External pages loaded inside the Browser guest remain page-owned. Presentation-only; no protocol, storage, host runtime, or external-page behavior change. See E2E-157.** | Windows' classic scrollbar made the right-side work-panel Files view visibly heavier than the conversation, while the sidebar retained a second scrollbar treatment. |
-| D-LOCAL-message-quotes | Message quotes and renderer-owned side chats | **Amend D209 / D301: every user message and assistant turn gains a Quote action that inserts a `> `-prefixed Markdown blockquote plus a `chat.quoteSource` attribution into the active session's composer draft and focuses it, using the live selection inside that message row when one exists and the message's own text otherwise; it never sends and adds no chip kind, with a 2000-character cap. Open side chat forks the anchored message through `session.fork` without activating the child, registers the child as a renderer-owned side chat of the parent, and opens one `sidechat:<childSessionId>` tab in the existing docked panel that streams from the same event stream through the background-transcript reducer, with Add to main chat, Open as a conversation, a compact Send/Stop input, and the existing permission card. Closing the tab or activating the child removes the registration; the durable child stays an ordinary session. No protocol, schema, IPC, or permission change. See ADR message-quotes-and-side-chats and E2E-CHAT-quote-prefill through E2E-CHAT-side-chat-close.** | Users needed to reuse an exact earlier message or answer and to ask a side question without replacing the visible main conversation, and the existing fork path always activated its child. *(Amended by D-LOCAL-selection-overlay: the excerpt is recovered from the rendered DOM as Markdown, and a selection inside a transcript row offers Add to chat, Ask in side chat, and Copy from a selection-following overlay.)* |
-| D-LOCAL-response-annotations | Response annotations as prompt attachments | **Amend D-LOCAL-message-quotes (decision 3) for assistant turns: selecting text in a response and choosing Add to chat attaches a numbered annotation to that turn instead of editing the composer draft — the answer body is not decorated (only a citation the model writes renders, as a numbered reference), the composer shows one annotation attachment chip whose tooltip lists the excerpts plus one control that drops them, and the next prompt carries them as `# Response annotations:` + an instruction + `<response-annotations>` JSON (`[{text, annotation, source:{messageId}}]`) + `## My request:` before the user's own text, consuming them. The visible draft, optimistic row, title, and edit seed stay annotation free, and a stored prompt carrying the block is displayed as its request. *(Amended 2026-09-12: Add to chat opens a compact comment editor whose Save writes the user's optional comment into the annotation; re-annotating an attached excerpt reopens that editor instead of a silent no-op, and the composer attachment lists each item with edit and remove controls beside clear-all.)* Quoting a user message, and the side chat's Add to main chat, keep D-LOCAL-message-quotes's draft quote; no protocol, storage-schema, IPC, or permission change. See ADR response-annotations and E2E-CHAT-annotation-attachments, E2E-CHAT-annotation-session-state.** | The draft quote copied the model's words into the user's own prompt text, and several referenced passes had no numbering the model could address; the reference implementation attaches them as numbered prompt data instead. |
+| D-LOCAL-message-quotes | Message quotes and renderer-owned side chats | *(retired by ADR 0268 on 2026-09-16)* **Amend D209 / D301: every user message and assistant turn gains a Quote action that inserts a `> `-prefixed Markdown blockquote plus a `chat.quoteSource` attribution into the active session's composer draft and focuses it, using the live selection inside that message row when one exists and the message's own text otherwise; it never sends and adds no chip kind, with a 2000-character cap. Open side chat forks the anchored message through `session.fork` without activating the child, registers the child as a renderer-owned side chat of the parent, and opens one `sidechat:<childSessionId>` tab in the existing docked panel that streams from the same event stream through the background-transcript reducer, with Add to main chat, Open as a conversation, a compact Send/Stop input, and the existing permission card. Closing the tab or activating the child removes the registration; the durable child stays an ordinary session. No protocol, schema, IPC, or permission change. See ADR message-quotes-and-side-chats and E2E-CHAT-quote-prefill through E2E-CHAT-side-chat-close.** | Users needed to reuse an exact earlier message or answer and to ask a side question without replacing the visible main conversation, and the existing fork path always activated its child. *(Amended by D-LOCAL-selection-overlay: the excerpt is recovered from the rendered DOM as Markdown, and a selection inside a transcript row offers Add to chat, Ask in side chat, and Copy from a selection-following overlay.)* |
+| D-LOCAL-response-annotations | Response annotations as prompt attachments | *(retired by ADR 0268 on 2026-09-16)* **Amend D-LOCAL-message-quotes (decision 3) for assistant turns: selecting text in a response and choosing Add to chat attaches a numbered annotation to that turn instead of editing the composer draft — the answer body is not decorated (only a citation the model writes renders, as a numbered reference), the composer shows one annotation attachment chip whose tooltip lists the excerpts plus one control that drops them, and the next prompt carries them as `# Response annotations:` + an instruction + `<response-annotations>` JSON (`[{text, annotation, source:{messageId}}]`) + `## My request:` before the user's own text, consuming them. The visible draft, optimistic row, title, and edit seed stay annotation free, and a stored prompt carrying the block is displayed as its request. *(Amended 2026-09-12: Add to chat opens a compact comment editor whose Save writes the user's optional comment into the annotation; re-annotating an attached excerpt reopens that editor instead of a silent no-op, and the composer attachment lists each item with edit and remove controls beside clear-all.)* Quoting a user message, and the side chat's Add to main chat, keep D-LOCAL-message-quotes's draft quote; no protocol, storage-schema, IPC, or permission change. See ADR response-annotations and E2E-CHAT-annotation-attachments, E2E-CHAT-annotation-session-state.** | The draft quote copied the model's words into the user's own prompt text, and several referenced passes had no numbering the model could address; the reference implementation attaches them as numbered prompt data instead. |
| D398 | Context usage display preference | **Amend D347 / ADR 0184: the context usage inspector's leading figure — the trigger ring arc, percentage, token label, popover heading, tooltip, and `aria-label` — is configurable via `AppSettings.contextUsageDisplay` (`"remaining"` or `"used"`). Default and fallback for absent/unrecognised values is `"remaining"`. When `"used"`, the ring fills by `usedRatio`, and text shows the used-capacity pair. Warning and critical color thresholds (remaining ≤ 25 % / ≤ 10 %) stay based on remaining capacity regardless of display mode. Settings → AI → Defaults adds a segmented control (Remaining / Used) after Link open destination and before Enter-to-send. Renderer only; no protocol, storage, host, or migration change. See ADR 0222 and E2E-250.** | The remaining-only display gave weak signal at low occupancy and did not match users who reason in terms of "how much have I spent". Color must stay on remaining to avoid a misleading green ring at 90 % used. |
| D399 | Project group manual ordering | *(amended by D402)* **Amend D093: retained project groups expose a visible-on-hover/focus grip. Native drag/drop and ArrowUp/ArrowDown on that grip write contiguous normalized-path `order` values and set `projectSort` to `manual` in renderer-local sidebar preferences. Archived and pinned priority remains ahead of manual order; project activation, host workspace identity, session ordering, and on-disk directories are unchanged.** | Users with several active repositories need a stable working order independent of recent activity or alphabetical names, while the existing path-keyed and host-owned project model remains untouched. |
| D400 | Restore deferred tools from effective session context | **Amend D185 / ADR 0048: before each new prompt and after a mode switch, clear the in-memory deferred activation set, then restore names from successful `ToolSearch` results (`addedToolNames`) and successful deferred-tool results in the effective `buildSessionContext` projection. Keep only names still in the current deferred catalog and mode; ignore errors, interrupted or missing-result placeholders, and assistant/user prose. No host permission or workspace boundary changes.** | Clearing activations while retaining their successful transcript markers left the model able to see a capability that was absent from the next provider schema. Reconstructing only from effective successful evidence keeps the provider request coherent without parsing prose or reviving stale or disallowed tools. See ADR 0225 and E2E-008a. |
@@ -86,7 +86,7 @@ This log freezes previously open questions into concrete decisions.
| D409 | Host-owned session collaboration messages | **Amend ADR 0237 / ADR 0165 / ADR 0213: Rust host-core owns a durable session-collaboration ledger keyed by message id and real source/target Session IDs. Plugin-mediated `spawn`, `send`, `status`, `result`, and `cancel` operations use the reviewed desktop-control gateway; the sender is bound to the active plugin Agent tool invocation, target turns retain their existing configuration, and each delivery is claimed by its actual durable turn. Completion callbacks are durable, at-most-once, and reference the settled turn. Provenance is persisted with transcript rows and cannot be forged, stripped, or edited through regeneration. The additive schema v16 migration retains queued work across restart without unattended replay, applies permission ceilings and bounded autonomous hops, and keeps the existing Task family unchanged. See ADR 0239 and E2E-PLUGIN-session-orchestrator-real-workers.** | The plugin's prior create/prompt polling path could infer neither a durable turn outcome nor a safe bidirectional sender identity. A host-owned ledger makes delivery, provenance, callback, cancellation, and restart behavior auditable without restoring the withdrawn A2A protocol. |
| D410 | Independent session discovery and navigable collaboration projections | **Amend ADR 0239: add the reviewed read operation `session/collaboration/list`, bounded to 100 non-deleted Agent sessions and redacted to Session IDs, titles, status, updated time, readable provider/model labels, and bounded creation links. Extend the sidebar projection with readable model labels and at most eight created-session references. Render creator/created-session references as keyboard-focusable navigation buttons; independent sessions do not receive fabricated creator links. No renderer storage ownership or collaboration mutation boundary changes. See ADR 0240, E2E-SESSION-independent-top-level-communication, and E2E-SESSION-hover-card-model-and-links.** | Existing Session IDs were valid send targets but could be undiscoverable when they were not created by the plugin, while the hover card exposed only IDs and non-interactive provenance. A bounded host directory and navigable projection make durable sessions communicable and explainable without exposing transcripts or credentials. |
| D413 | Skill market public-HTTPS catalog fetch | **Additive: Settings → Skills Market discovers SKILL.md catalogs in Electron main under a shared public-HTTPS policy (syntactic public host + DNS classification + per-hop redirect re-validation). The renderer does not fetch. Install remains `skills.create`. Catalog ids match host `valid_capability_id`. Expanded documents over 128 KiB are refused. Builtin titles are English. See ADR 0243, E2E-SKILL-MARKET-*, issue #287.** | Community skill discovery needs main-process egress without a plugin-marketplace host allowlist, and copied classifiers would collide with the MCP market. |
-| D421 | Native Pi session continuation | **Amend baseline D007: discover Pi v3 sessions as source-discriminated projections and continue them through coding-agent `AgentSession`/`SessionManager` against their canonical JSONL. Rust remains authoritative for Desktop SQLite/transcripts. Native continuation requires exact saved provider/auth, project trust, canonical path/header identity, and a cooperative lease plus byte/leaf validation; failures remain browseable/read-only. First slice excludes native rename/delete/move/revisions/Plan/Goal/queue/collaboration; the 2026-09-14 ADR 0254 amendment adds native fork and persistent side chats with exact stream re-keying and inode-tracked publication. See ADR 0254 and E2E-SESSION-native-pi-*/E2E-SESSION-native-side-chat-*.** | Importing a flattened copy cannot preserve Pi's tree or make later Desktop turns visible to Pi Web. |
+| D421 | Native Pi session continuation | **Amend baseline D007: discover Pi v3 sessions as source-discriminated projections and continue them through coding-agent `AgentSession`/`SessionManager` against their canonical JSONL. Rust remains authoritative for Desktop SQLite/transcripts. Native continuation requires exact saved provider/auth, project trust, canonical path/header identity, and a cooperative lease plus byte/leaf validation; failures remain browseable/read-only. First slice excludes native rename/delete/move/revisions/Plan/Goal/queue/collaboration; the 2026-09-14 ADR 0254 amendment adds native fork with exact stream re-keying and inode-tracked publication; the side-chat panel it added is retired by ADR 0268. See ADR 0254 and E2E-SESSION-native-pi-*.** | Importing a flattened copy cannot preserve Pi's tree or make later Desktop turns visible to Pi Web. |
| D412 | Delta-only coalesced streaming updates | **Amend the local `message_update` contract: append-only streaming frames carry `stream: delta` plus `deltaText`/`deltaThinking` (and reset flags) without growing `content`/`thinking`. Runtime coalesces those frames every 16ms and flushes before semantic boundaries. AgentHost, inflight checkpoints, and the renderer apply deltas; `message_start`/`message_end` remain full snapshots. Transcript activity parts keep object identity when only the tail token changes. Protocol version stays 11. See ADR 0242, E2E-STREAM-long-turn-keeps-realtime, and issue #299.** | Each token re-serialized the full assistant snapshot across sidecar, AgentHost, and IPC, so a long turn cost O(n²) bytes and backlogged later short chunks. |
| D416 | Git clone accepts only syntactically public hosts | **Amend home git clone: `parseGitCloneUrl` reuses `isPublicHostname` so loopback, private, CGNAT, link-local, ULA, and `.local`/`.localhost` remotes are rejected before `git clone` runs. HTTPS/HTTP/SSH/`git@host:path` to public hosts remain valid. `file:` and URL passwords stay rejected. Git still performs its own DNS; this is not a market-style pin. See ADR 0247 and E2E-CLONE-public-hostname-rejects-private.** | Clone accepted `http://127.0.0.1/...` and RFC1918 literals, which is a LAN/SSRF hole the market fetchers already close for HTTPS catalogs. |
| D417 | Plugin runtime theme APIs + sidebar image token | **Add `pi.app.setTheme` and `pi.themes.upsert`/`remove`/`list` under `ui.theme` (ADR 0260 / issue #352). Remove `MAX_THEMES_PER_PLUGIN`. Runtime upsert sanitizes CSS like load-time registration and emits `pluginChanged` (`reason: "themes"`); `setTheme` persists `AppSettings.theme` and emits `settingsChanged`. Split sidebar paint: `--ds-bg-sidebar` stays a color; optional `--ds-bg-sidebar-image` holds gradients/images, with macOS vibrancy stacking sheen over the image layer.** | Theme editor plugins cannot apply a theme from their panel, cannot ship an unlimited library, and cannot live-edit production CSS without reload; sidebar gradients broke `color-mix` / vibrancy consumers when stuffed into the color token. |
@@ -980,6 +980,8 @@ section mirrors only marketplace/catalog items still blocking nothing.
E2E-102i.
## 2026-09-11 — Message quotes and renderer-owned side chats (D-LOCAL-message-quotes)
+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*
+
- Every user message and every assistant turn gains a Quote action beside Copy,
Edit, Delete, Fork, and Retry. It inserts a `> `-prefixed Markdown blockquote
plus a `chat.quoteSource` attribution line into the active session's composer
@@ -4668,6 +4670,8 @@ D193, and D194.
## 2026-09-11 — Selection overlay for quotes (D-LOCAL-selection-overlay)
+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*
+
- Quote no longer has to be reached at the end of the answer: a non-empty text
selection inside one transcript row floats one overlay **above** it, centered
on the selection and clamped into its clipping ancestors' rects (the transcript
@@ -4699,6 +4703,8 @@ D193, and D194.
## 2026-09-11 — Response annotations as prompt attachments (D-LOCAL-response-annotations)
+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*
+
- Selecting text in an assistant turn and choosing Add to chat attaches a
**numbered annotation** to that turn: an id, the anchored turn, the excerpt
(Markdown, 2000-character cap), an empty comment field, and capture order as
@@ -5023,6 +5029,8 @@ Validation contract: E2E-SIDEBAR-global-pinned-conversations.
## 2026-09-14 — Preserve local annotation and side-chat contracts across upstream integration
+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*
+
- Local ADRs now use semantic names `message-quotes-and-side-chats`,
`response-annotations`, and `floating-annotation-index`; former local 0223–0225
collided with upstream ADRs. Local D398–D400 references use `D-LOCAL-*`, and
@@ -5282,6 +5290,8 @@ OAuth login, token refresh, or account label today.
## 2026-09-15 — Side chats materialize on first Send (#421)
+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*
+
Side-chat opening and selection quote prefill are renderer-only drafts. The
first explicit nonempty Send creates the anchored child, with concurrent
submissions deduplicated and failed drafts retained. Closing unsent drafts
@@ -5443,3 +5453,27 @@ that was sitting at the bottom — including after the turn had finished.
- See ADR 0266, `07-plugins/03-plugin-api.md` §3,
`07-plugins/13-plugin-permissions-matrix.md` §6, and
E2E-PLUGIN-fs-root-follows-the-calling-session.
+
+## 2026-09-16 — Quotes, annotations, and side chats are removed (ADR 0268)
+
+- Quote, the text-selection overlay, response annotations (comment editor,
+ floating index, source badges, composer attachment), and renderer-owned side
+ chats are removed from every surface. Message action rows keep Copy, Edit,
+ Delete, Fork, Retry, and Regenerate; the composer keeps its draft, chips, smart
+ Stop, and per-session draft slots; the work panel keeps its other tab kinds;
+ `session.fork` and the Fork action are unchanged.
+- Sends no longer compose a `# Response annotations:` block, and the display-side
+ reduction `requestTextWithoutAnnotations` is gone, so a prompt stored before the
+ removal is shown exactly as it was stored in the transcript, the edit seed, and
+ the queue preview.
+- Retired and never reusable: `D-LOCAL-message-quotes`, `D-LOCAL-selection-overlay`,
+ `D-LOCAL-response-annotations`, `D-native-sidechat-stream`, and the E2E IDs
+ E2E-CHAT-quote-prefill, E2E-CHAT-selection-markdown,
+ E2E-CHAT-selection-side-chat, E2E-CHAT-annotation-attachments,
+ E2E-CHAT-annotation-session-state, E2E-CHAT-annotation-source-index,
+ E2E-CHAT-annotation-ack-and-steering, E2E-CHAT-side-chat-fork,
+ E2E-CHAT-side-chat-stream, E2E-CHAT-side-chat-add-to-main,
+ E2E-CHAT-side-chat-promote, E2E-CHAT-side-chat-close, and
+ E2E-SESSION-native-side-chat-fork-survives-close.
+- No host protocol (v11), storage schema (v15), IPC channel, permission, or Rust
+ change. See ADR 0268.
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 06e91ce92..dea31cd2c 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -1197,7 +1197,7 @@ tail 不得将该寻呼机从用户气泡中移动或分离。寻呼机是
### 8.6 MVP 约束
-- 无消息 reactions/annotations
+- 无消息 reactions
- 无法编辑用户消息(推迟)
- 复制助手答案不包括思考文本
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index 59c52b903..50e3a8254 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -74,8 +74,8 @@
| D393 | Composer 中用户调用的 Skills | **修订 D123 / D174 / ADR 0024 / ADR 0039:激活的内置、插件和用户 Skills 出现在 composer slash 菜单末尾独立的 `Skills` 分组中。选择后插入其精确 id;Electron main 在发送时重新验证当前项目范围,并要求模型调用本地 `Skill` 工具,同时保留按需加载正文和现有权限。现有命令名优先解决冲突;未激活的 Skills 保持为字面 slash 文本。见 ADR 0219 和 E2E-088b。** | D174 的模型调用目录仍是 Skill 正文加载和安全契约,但拒绝面向用户的 slash 条目使已经知道工作流的用户难以发现活跃 Skills。 |
| D394 | Windows 工作面板 chrome 保持单一资源操作组 | **修订 D154 / D357 / ADR 0195:打开的工作面板标题栏只保留一个紧凑资源切换器;资源关闭由现有可键盘操作的上下文菜单行负责,视口固定开关仍是唯一的面板折叠控件,子代理详情使用返回箭头。Windows/Linux 原生控件仍固定在窗口边缘。仅渲染器变更;不改面板状态、窗口几何、IPC、协议或存储。见 ADR 0220 与 E2E-067。** | 标题栏资源 `X`、视口固定开关和 Windows 原生关闭按钮在窄面板中看起来像重复的关闭操作,并且过于拥挤。 |
| D396 | 渲染器与插件面板滚动条统一为紧凑规则 | **修订 D300:渲染器中的每个滚动容器统一使用 6px、无轨道、静止时透明的滚动条,以及相同的悬停、focus-within、滚动显示和拖动状态。移除侧边栏专用的宽度和透明度覆盖。插件面板 preload 给停靠和独立插件文档(包括内置 Files 视图)注入同一规则和 300ms 的滚动显示标记。Browser 内部加载的外部网页仍由网页自己管理。仅表现层变更;不改变协议、存储、主机运行时或外部网页行为。见 E2E-157。** | Windows 的经典滚动条让右侧工作面板的 Files 视图明显比对话区更粗,而侧边栏还保留了第二套滚动条样式。 |
-| D-LOCAL-message-quotes | 消息引用与渲染器拥有的侧边聊天 | **修订 D209 / D301:每条用户消息和每个助手回合的悬停操作行新增 Quote 操作,与 Copy、Edit、Delete、Fork、Retry 并列。它把以 `> ` 开头的 Markdown 引用块加一行 `chat.quoteSource` 归属写入当前会话的 composer 草稿并聚焦输入框;选区位于被点击消息行内时使用该选区,否则使用消息自身文本;摘录上限 2000 字符并带省略号;绝不发送,也不新增任何芯片类型。Open side chat 通过 `session.fork` 以锚点消息分叉且不激活子会话,把子会话注册为父会话的渲染器侧边聊天,并在现有停靠面板中打开一个 `sidechat:<childSessionId>` 标签,用同一条事件流经后台转录 reducer 实时流式渲染,提供 Add to main chat、Open as a conversation、紧凑 Send/Stop 输入和现有权限卡。关闭标签或以会话方式打开子会话会移除注册;持久子会话仍是普通会话。不改协议、schema、IPC 或权限。见 ADR message-quotes-and-side-chats 与 E2E-CHAT-quote-prefill 至 E2E-CHAT-side-chat-close。** | 用户需要复用之前某条消息或答案的原文,并在不替换当前可见主对话的前提下追问一个旁支问题,而现有 fork 路径总会激活子会话。 *(由 D-LOCAL-selection-overlay 修订:摘录改为从渲染后的 DOM 还原为 Markdown,且消息行内的选区可在跟随选区的浮层中选择「添加到对话」「在侧边聊天中提问」或复制。)* |
-| D-LOCAL-response-annotations | 响应批注作为提示词附件 | **对助手回合修订 D-LOCAL-message-quotes 决定 3:在响应中选中文字并选择「添加到对话」时,把编号批注附加到该回合,而不是改写 composer 草稿——回答正文不被装饰(只有模型写出的引用才渲染为编号引用),composer 显示一个批注附件芯片(提示中列出各条摘录,并提供一键清除),下一条提示在用户自己的文字之前携带 `# Response annotations:` + 指令 + `<response-annotations>` JSON(`[{text, annotation, source:{messageId}}]`)+ `## My request:`,并消费这些批注。可见草稿、乐观行、标题与编辑种子都不含批注内容,已存提示在展示时会还原为用户请求。*(2026-09-12 修订:「添加到对话」会打开一个紧凑的评论编辑器,保存时把用户可选的评论写入批注的 `annotation`;再次批注同一摘录会重新打开该批注的编辑器,而不再是静默无操作;composer 附件会列出每条批注,并提供逐条编辑与移除,清除全部仍然保留。)* 引用用户消息以及侧边聊天的 Add to main chat 仍沿用 D-LOCAL-message-quotes 的草稿引用;不改协议、存储 schema、IPC 或权限。见 ADR response-annotations 与 E2E-CHAT-annotation-attachments、E2E-CHAT-annotation-session-state。** | 草稿引用会把模型的话混进用户自己的提示文本,且多处引用没有模型可寻址的编号;参考实现改为把摘录作为带编号的提示数据附加。 |
+| D-LOCAL-message-quotes | 消息引用与渲染器拥有的侧边聊天 | *(已由 ADR 0268 于 2026-09-16 退役)* **修订 D209 / D301:每条用户消息和每个助手回合的悬停操作行新增 Quote 操作,与 Copy、Edit、Delete、Fork、Retry 并列。它把以 `> ` 开头的 Markdown 引用块加一行 `chat.quoteSource` 归属写入当前会话的 composer 草稿并聚焦输入框;选区位于被点击消息行内时使用该选区,否则使用消息自身文本;摘录上限 2000 字符并带省略号;绝不发送,也不新增任何芯片类型。Open side chat 通过 `session.fork` 以锚点消息分叉且不激活子会话,把子会话注册为父会话的渲染器侧边聊天,并在现有停靠面板中打开一个 `sidechat:<childSessionId>` 标签,用同一条事件流经后台转录 reducer 实时流式渲染,提供 Add to main chat、Open as a conversation、紧凑 Send/Stop 输入和现有权限卡。关闭标签或以会话方式打开子会话会移除注册;持久子会话仍是普通会话。不改协议、schema、IPC 或权限。见 ADR message-quotes-and-side-chats 与 E2E-CHAT-quote-prefill 至 E2E-CHAT-side-chat-close。** | 用户需要复用之前某条消息或答案的原文,并在不替换当前可见主对话的前提下追问一个旁支问题,而现有 fork 路径总会激活子会话。 *(由 D-LOCAL-selection-overlay 修订:摘录改为从渲染后的 DOM 还原为 Markdown,且消息行内的选区可在跟随选区的浮层中选择「添加到对话」「在侧边聊天中提问」或复制。)* |
+| D-LOCAL-response-annotations | 响应批注作为提示词附件 | *(已由 ADR 0268 于 2026-09-16 退役)* **对助手回合修订 D-LOCAL-message-quotes 决定 3:在响应中选中文字并选择「添加到对话」时,把编号批注附加到该回合,而不是改写 composer 草稿——回答正文不被装饰(只有模型写出的引用才渲染为编号引用),composer 显示一个批注附件芯片(提示中列出各条摘录,并提供一键清除),下一条提示在用户自己的文字之前携带 `# Response annotations:` + 指令 + `<response-annotations>` JSON(`[{text, annotation, source:{messageId}}]`)+ `## My request:`,并消费这些批注。可见草稿、乐观行、标题与编辑种子都不含批注内容,已存提示在展示时会还原为用户请求。*(2026-09-12 修订:「添加到对话」会打开一个紧凑的评论编辑器,保存时把用户可选的评论写入批注的 `annotation`;再次批注同一摘录会重新打开该批注的编辑器,而不再是静默无操作;composer 附件会列出每条批注,并提供逐条编辑与移除,清除全部仍然保留。)* 引用用户消息以及侧边聊天的 Add to main chat 仍沿用 D-LOCAL-message-quotes 的草稿引用;不改协议、存储 schema、IPC 或权限。见 ADR response-annotations 与 E2E-CHAT-annotation-attachments、E2E-CHAT-annotation-session-state。** | 草稿引用会把模型的话混进用户自己的提示文本,且多处引用没有模型可寻址的编号;参考实现改为把摘录作为带编号的提示数据附加。 |
| D398 | 上下文用量显示偏好 | **修订 D347 / ADR 0184:上下文用量检查器的引导数值——触发器圆弧(`strokeDashoffset`)、百分比、令牌标签、弹层标题、tooltip 与 `aria-label`——可通过 `AppSettings.contextUsageDisplay`(`"remaining"` 或 `"used"`)配置。缺省及非法值回退为 `"remaining"`。当设为 `"used"` 时,圆环按 `usedRatio` 填充,文字展示已用容量对。警告与临界颜色阈值(剩余 ≤ 25 % / ≤ 10 %)仍按剩余容量判定,不随显示模式变化。设置 → 全局 AI → 默认项新增分段控件(剩余 / 已用),位于链接打开目标之后、回车发送之前。仅渲染器改动;无协议、存储、宿主或迁移变更。见 ADR 0222 与 E2E-250。** | 仅显示剩余时在低占用下信号微弱,且不符合习惯用「已用多少」思考的用户。颜色必须始终按剩余判定,否则已用 90 % 仍为绿色会产生误导。 |
| D399 | 项目组手动排序 | *(由 D402 修订)* **修订 D093:保留的项目组显示悬停/聚焦可见的手柄。原生拖放以及在手柄上按 `ArrowUp`/`ArrowDown` 会按规范化路径写入连续的 `order` 值,并在渲染器本地的侧边栏偏好中将 `projectSort` 设为 `manual`。归档和置顶优先级仍高于手动顺序;项目激活、主机工作区身份、会话顺序和磁盘目录保持不变。** | 多个活动仓库需要不受最近活动或名称影响的稳定工作顺序,同时保持现有按路径索引且由主机拥有的项目模型不变。 |
| D400 | 从有效会话上下文恢复延迟工具 | **修订 D185 / ADR 0048:每个新提示和模式切换前,清除内存中的延迟激活集,然后从有效 `buildSessionContext` 投影中的成功 `ToolSearch` 结果(`addedToolNames`)和成功的延迟工具结果恢复名称。仅保留当前延迟目录和模式仍允许的名称;忽略错误、已中断或缺少结果的占位行,以及助手/用户文本。不改变主机权限或工作区边界。** | 清除激活却保留成功的转录标记,会让模型看到能力证据而下一次 provider schema 中没有对应工具。只从有效的成功证据恢复,既保持 provider 请求一致,也不解析文本或复活过时、被禁止的工具。见 ADR 0225 与 E2E-008a。 |
@@ -89,7 +89,7 @@
| D409 | 宿主拥有的会话协作消息 | **修订 ADR 0237 / ADR 0165 / ADR 0213:Rust host-core 拥有以消息 id 和真实源/目标 Session ID 为键的持久会话协作 ledger。插件驱动的 `spawn`、`send`、`status`、`result` 和 `cancel` 使用已审查的 desktop-control 网关;发送者绑定当前插件 Agent 工具调用,目标回合保留原有配置,每条投递由实际持久回合认领。完成回调持久化且最多一次,并引用已结算回合。来源信息随转录行持久化,不能在重生成中伪造、剥离或编辑。增量架构 v16 迁移在重启后保留排队工作但不无人值守重放,执行权限上限和有界自主跳数,同时保持既有 Task 系列不变。见 ADR 0239 与 E2E-PLUGIN-session-orchestrator-real-workers。** | 插件之前的创建/提示轮询路径既无法推断持久回合结果,也无法安全确认双向发送者身份。宿主拥有的 ledger 让投递、来源、回调、取消和重启行为可审计,同时不恢复已撤回的 A2A 协议。 |
| D410 | 独立会话发现与可导航协作投影 | **修订 ADR 0239:新增经审查的 `session/collaboration/list` 读取操作,限制为最多 100 个未删除 Agent 会话,并只返回 Session ID、标题、状态、更新时间、可读 provider/model 标签和有界创建关系。侧边栏投影增加可读模型标签和最多八个已创建会话引用。创建者/已创建会话引用渲染为可键盘聚焦的导航按钮;独立会话不伪造创建者链接。不改变渲染器存储归属或协作写入边界。见 ADR 0240、E2E-SESSION-independent-top-level-communication 和 E2E-SESSION-hover-card-model-and-links。** | 现有 Session ID 虽然是有效发送目标,但未由插件创建的会话可能不可发现;hover 卡片也只暴露 ID,来源信息不可交互。有界 host 目录和可导航投影让持久会话可通信、可解释,同时不暴露转录或凭据。 |
| D413 | 技能市场公网 HTTPS 目录拉取 | **增量:设置 → 技能市场由 Electron 主进程按共享公网 HTTPS 策略发现 SKILL.md(公网主机语法 + DNS 分类 + 逐跳 redirect)。渲染层不发网。安装仍走 `skills.create`。目录 id 与 host `valid_capability_id` 对齐。展开后超过 128 KiB 拒绝写入。内置标题为英文。见 ADR 0243、E2E-SKILL-MARKET-*、issue #287。** | 社区技能发现需要主进程出网,且不能复用插件市场的主机允许列表;复制分类器会与 MCP 市场撞名。 |
-| D421 | Native Pi 会话续接 | **修订基线 D007:把 Pi v3 会话发现为按来源区分的投影,并通过 coding-agent `AgentSession`/`SessionManager` 针对其规范 JSONL 继续会话。Rust host-core 仍是 Desktop SQLite/Desktop 成绩单的权威;原生回合不进入 Desktop outbox,也不产生导入副本。原生续接要求精确的已存 provider/auth、项目信任、规范路径/头身份,以及带字节/叶节点校验的协作租约;失败保持可浏览/只读。首片不含原生 rename/delete/move/revisions/Plan/Goal/queue/collaboration;2026-09-14 的 ADR 0254 修订加入原生 fork 与持久侧聊,含精确流重键与 inode 跟踪的发布。见 ADR 0254 与 E2E-SESSION-native-pi-*/E2E-SESSION-native-side-chat-*。** | 导入扁平副本无法保留 Pi 的树结构,也无法让之后 Desktop 的回合对 Pi Web 可见。 |
+| D421 | Native Pi 会话续接 | **修订基线 D007:把 Pi v3 会话发现为按来源区分的投影,并通过 coding-agent `AgentSession`/`SessionManager` 针对其规范 JSONL 继续会话。Rust host-core 仍是 Desktop SQLite/Desktop 成绩单的权威;原生回合不进入 Desktop outbox,也不产生导入副本。原生续接要求精确的已存 provider/auth、项目信任、规范路径/头身份,以及带字节/叶节点校验的协作租约;失败保持可浏览/只读。首片不含原生 rename/delete/move/revisions/Plan/Goal/queue/collaboration;2026-09-14 的 ADR 0254 修订加入原生 fork,含精确流重键与 inode 跟踪的发布;该修订加入的侧边聊天面板已由 ADR 0268 移除。见 ADR 0254 与 E2E-SESSION-native-pi-*。** | 导入扁平副本无法保留 Pi 的树结构,也无法让之后 Desktop 的回合对 Pi Web 可见。 |
| D412 | 仅增量且合并的流式更新 | **修订本地 `message_update` 契约:追加型流式帧携带 `stream: delta` 以及 `deltaText`/`deltaThinking`(和 reset 标志),不再附带增长中的 `content`/`thinking`。运行时每 16ms 合并这些帧,并在语义边界前立即 flush。AgentHost、进行中检查点和渲染器应用增量;`message_start`/`message_end` 仍是完整快照。仅尾部 token 变化时,转录活动 part 保持对象身份。协议版本仍为 11。见 ADR 0242、E2E-STREAM-long-turn-keeps-realtime 和 issue #299。** | 每个 token 都在 sidecar、AgentHost 和 IPC 上重新序列化完整助手快照,长回合接近 O(n²) 字节并让后续短块排队变慢。 |
| D416 | Git clone 只接受语法上的公网主机 | **修订首页 Git clone:`parseGitCloneUrl` 复用 `isPublicHostname`,在运行 `git clone` 前拒绝回环、私网、CGNAT、链路本地、ULA 以及 `.local`/`.localhost` 远程。指向公网主机的 HTTPS/HTTP/SSH/`git@host:path` 仍然有效。`file:` 和 URL 密码继续拒绝。Git 仍自己做 DNS;这不是市场那种地址固定。见 ADR 0247 与 E2E-CLONE-public-hostname-rejects-private。** | clone 曾接受 `http://127.0.0.1/...` 和 RFC1918 字面量,这是市场 HTTPS 拉取已经关掉的局域网/SSRF 缺口。 |
| D417 | 插件运行时主题 API + 侧栏图像令牌 | **在 `ui.theme` 下新增 `pi.app.setTheme` 与 `pi.themes.upsert`/`remove`/`list`(ADR 0260 / issue #352)。移除 `MAX_THEMES_PER_PLUGIN`。运行时 upsert 与加载期相同的 CSS 消毒,并发出 `pluginChanged`(`reason: "themes"`);`setTheme` 持久化 `AppSettings.theme` 并发出 `settingsChanged`。拆分侧栏绘制:`--ds-bg-sidebar` 保持颜色;可选 `--ds-bg-sidebar-image` 承载渐变/图片,macOS vibrancy 在图像层之上叠加 sheen。** | 主题编辑插件无法在面板内应用主题,无法提供不限量主题库,也无法在生产模式免重载实时改 CSS;把渐变塞进颜色令牌会破坏 `color-mix` / vibrancy 消费方。 |
@@ -3856,6 +3856,8 @@ D193 和 D194。
`04-ux/07-ui-design-system.md`、`04-ux/08-component-spec.md` 与 E2E-157。
## 2026-09-11 —— 消息引用与渲染器拥有的侧边聊天(D-LOCAL-message-quotes)
+*(已由 ADR 0268 于 2026-09-16 退役:功能与相关界面均已移除,这些 ID 永久退役且不得复用;此处记录仅作历史留存。)*
+
- 每条用户消息和每个助手回合新增 Quote 操作,与 Copy、Edit、Delete、Fork、Retry 并列。
它把以 `> ` 开头的 Markdown 引用块加一行 `chat.quoteSource` 归属写入当前会话的
composer 草稿,选区在被点击消息行内时使用选区、否则使用消息自身文本,摘录上限
@@ -3870,6 +3872,8 @@ D193 和 D194。
## 2026-09-11 —— 选区的引用浮层(D-LOCAL-selection-overlay)
+*(已由 ADR 0268 于 2026-09-16 退役:功能与相关界面均已移除,这些 ID 永久退役且不得复用;此处记录仅作历史留存。)*
+
- 引用不再必须回到答案末尾。消息行内存在非空文本选区时,在选区**上方**悬浮一个浮层:水平居中于选区,限制在
裁剪祖先(转录滚动容器)的矩形内,并且不越过停靠输入区的顶边;浮层按应用其他 body portal 浮层的方式挂载,
并在对话滚动时跟随选区移动,而不是直接消失。
@@ -3888,6 +3892,8 @@ D193 和 D194。
## 2026-09-11 —— 响应批注作为提示词附件(D-LOCAL-response-annotations)
+*(已由 ADR 0268 于 2026-09-16 退役:功能与相关界面均已移除,这些 ID 永久退役且不得复用;此处记录仅作历史留存。)*
+
- 在助手回合中选中文字并选择「添加到对话」,会为该回合附加一条**带编号的批注**:id、锚定的回合、摘录(Markdown,
上限 2000 字符)、空的评论字段,以及作为编号的捕获顺序。批注属于渲染器侧的会话状态;重复批注同一摘录不生效,
既不持久化,也不单独发送给宿主。
@@ -4050,7 +4056,8 @@ D193 和 D194。
The authoritative English amendment documents semantic local ADR/E2E identities,
acknowledgement-scoped annotation consumption, text-only Alt+Enter steering, and
-the retained upstream work-panel lifecycle. See
+the retained upstream work-panel lifecycle. The annotation and side-chat parts of
+that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays. See
[the English decision log](../../../spec/08-meta/decisions-log.md#_2026-09-14-preserve-local-annotation-and-side-chat-contracts-across-upstream-integration).
## 2026-09-14 —— Git clone 只接受语法上的公网主机(D416)
@@ -4212,3 +4219,10 @@ the retained upstream work-panel lifecycle. See
- 现在没有可见工作区时会话根也能解析,所以临时对话按会话各自继续工作,而不是所有会话一起失败;这种状态下的面板调用仍然失败关闭。于是 `workspace` 根的 `NOT_FOUND` 更窄:既没有解析出调用会话的项目,也没有可见工作区。
- 权限、realpath 包含、拒绝名单、声明范围与运行时同意这四类闸门都没有改动,插件 API 表面也未变化:`pi.workspace.get` 仍然以可见工作区及其项目组作答。
- 见 ADR 0266、`07-plugins/03-plugin-api.md` §3、`07-plugins/13-plugin-permissions-matrix.md` §6 与 E2E-PLUGIN-fs-root-follows-the-calling-session。
+
+## 2026-09-16 —— 引用、批注与侧边聊天已移除(ADR 0268)
+
+- 引用、文本选区浮层、响应批注(评论编辑器、悬浮批注索引、源标记、composer 批注附件)与渲染器拥有的侧边聊天已从所有界面移除。消息操作行保留 Copy、Edit、Delete、Fork、Retry 与 Regenerate;composer 保留草稿、芯片、智能 Stop 与会话级草稿槽;工作面板保留其余标签类型;`session.fork` 与 Fork 操作不变。
+- 发送路径不再拼装 `# Response annotations:` 块,显示层还原函数 `requestTextWithoutAnnotations` 一并删除,因此移除之前已存入会话的提示词在转录、编辑种子与队列预览中都按存储原文显示。
+- 永久退役且不得复用:`D-LOCAL-message-quotes`、`D-LOCAL-selection-overlay`、`D-LOCAL-response-annotations`、`D-native-sidechat-stream`,以及 E2E-CHAT-quote-prefill、E2E-CHAT-selection-markdown、E2E-CHAT-selection-side-chat、E2E-CHAT-annotation-attachments、E2E-CHAT-annotation-session-state、E2E-CHAT-annotation-source-index、E2E-CHAT-annotation-ack-and-steering、E2E-CHAT-side-chat-fork、E2E-CHAT-side-chat-stream、E2E-CHAT-side-chat-add-to-main、E2E-CHAT-side-chat-promote、E2E-CHAT-side-chat-close、E2E-SESSION-native-side-chat-fork-survives-close。
+- 未改动宿主协议(v11)、存储 schema(v15)、IPC 通道、权限与 Rust 侧。见 ADR 0268。
diff --git a/package.json b/package.json
index 8cd5c18ee..fce264a18 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,6 @@
"test:e2e:transcript-disclosure": "node scripts/e2e-transcript-disclosure-anchor.mjs",
"test:e2e:provider-api-style": "node scripts/e2e-provider-api-style.mjs",
"test:e2e:oauth-retry": "node --test apps/desktop/test/anthropic-oauth-retry.test.mjs",
- "test:e2e:native-side-chat": "node scripts/e2e-native-side-chat.mjs",
"test:e2e:boot": "node scripts/e2e-electron-boot.mjs",
"test:e2e:layout": "node scripts/e2e-three-column-layout.mjs",
"test:e2e:supervision": "node scripts/e2e-supervision.mjs",
diff --git a/packages/agent-runtime/src/native-pi-session.test.ts b/packages/agent-runtime/src/native-pi-session.test.ts
index 3b9013eb3..bc759a7ee 100644
--- a/packages/agent-runtime/src/native-pi-session.test.ts
+++ b/packages/agent-runtime/src/native-pi-session.test.ts
@@ -384,7 +384,7 @@ describe("native continuation review regressions", () => {
});
-describe("native side-chat forks", () => {
+describe("native fork children", () => {
function forkFixture() {
const root = mkdtempSync(join(tmpdir(), "pi-desktop-native-fork-"));
roots.push(root);
@@ -441,7 +441,7 @@ describe("native side-chat forks", () => {
const [summary] = await service.list();
const parentBytes = readFileSync(f.file, "utf8");
const before = groupEntries(f.group);
- const child = service.fork({ id: summary.id, title: "Side chat: hello" });
+ const child = service.fork({ id: summary.id, title: "Fork: hello" });
const childPath = newChildPath(f, before);
const childEntries = readFileSync(childPath, "utf8").trimEnd().split("\n").map((line) => JSON.parse(line));
@@ -458,11 +458,11 @@ describe("native side-chat forks", () => {
// The child continues the parent from the branch endpoint, and the
// parent is byte-identical after the fork.
expect(readFileSync(f.file, "utf8")).toBe(parentBytes);
- expect(child.title).toBe("Side chat: hello");
+ expect(child.title).toBe("Fork: hello");
expect(child.messages.map((message) => message.content)).toEqual(["hello", "first answer", "compacted", "second answer"]);
expect(child).toMatchObject({ source: "pi-native", modelId: "test-model", thinkingLevel: "high" });
expect(child.capabilities?.canPrompt).toBe(true);
- expect(service.detail(child.id)?.title).toBe("Side chat: hello");
+ expect(service.detail(child.id)?.title).toBe("Fork: hello");
} finally { service.disposeAll(); }
});
diff --git a/packages/agent-runtime/src/native-pi-session.ts b/packages/agent-runtime/src/native-pi-session.ts
index 5242c43f0..c309650ad 100644
--- a/packages/agent-runtime/src/native-pi-session.ts
+++ b/packages/agent-runtime/src/native-pi-session.ts
@@ -395,7 +395,7 @@ class NativePiRuntime {
} else if (event.type === "message_start") {
// The durable entry id is minted when the SDK appends the finished
// message, so the live row carries a provisional id that the renderer
- // replaces on `message_end` (D-native-sidechat-stream).
+ // replaces on `message_end`.
if (event.message.role === "assistant") {
const content = textContent((event.message as { content?: unknown }).content);
this.currentAssistant = {
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 37b0880e1..2b4476929 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -310,24 +310,6 @@ export const de = {
"openFile": "Mit Standardanwendung öffnen",
"retry": "Neu generieren",
"forkResponse": "Zweig aus dieser Antwort",
- "quote": "Zitieren",
- "annotate": "Anmerkung hinzufügen",
- "annotationMarker": "Anmerkung {index}",
- "annotationSelectedText": "Ausgewählter Text:",
- "annotationComment": "Nutzerkommentar:",
- "annotationCommentTitle": "Kommentar",
- "annotationCommentPlaceholder": "Kommentar hinzufügen",
- "annotationEdit": "Kommentar bearbeiten",
- "annotationRemove": "Anmerkung entfernen",
- "annotationReview": "Anmerkungen prüfen",
- "annotationLocate": "Anmerkung finden",
- "annotationRowLocation": "Originaltext nicht verfügbar; ursprüngliche Antwort wird angezeigt",
- "annotationChip": "{{count}} Anmerkungen",
- "clearAnnotations": "Anmerkungen löschen",
- "quoteSource": "Zitiert aus {{title}}",
- "addToChat": "Zum Chat hinzufügen",
- "askInSideChat": "Im Seitenchat fragen",
- "startSideChat": "Seitenchat öffnen",
"editMessage": "Bearbeiten und erneut senden",
"cancelEdit": "Abbrechen",
"retryEdit": "Wiederholen",
@@ -517,16 +499,6 @@ export const de = {
"thinkingEnable": "Denken aktivieren",
"untitledTask": "Neue Aufgabe"
},
- "sideChat": {
- parentBusy: "Das Hauptgespräch antwortet noch. Warte auf das Ende, bevor du diesen Seitenchat startest.",
- readOnly: "Diese native Pi-Sitzung ist derzeit schreibgeschützt.",
- "title": "Seitenchat",
- "sessionTitle": "Seitenchat: {{title}}",
- "placeholder": "Stellen Sie eine Rückfrage zu dieser Antwort",
- "empty": "Fragen Sie hier, ohne die Hauptkonversation zu ändern.",
- "addToMain": "Zum Hauptchat hinzufügen",
- "openAsSession": "Als Konversation öffnen"
- },
"session": {
"renameTitle": "Aufgabe umbenennen",
"renameAction": "Aufgabe umbenennen {{title}}",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 8969cc355..9bfecae6f 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -317,24 +317,6 @@ export const en = {
openFile: "Open with default application",
retry: "Regenerate",
forkResponse: "Branch from this reply",
- quote: "Quote",
- annotate: "Annotate",
- annotationMarker: "Annotation {index}",
- annotationSelectedText: "Selected text:",
- annotationComment: "User comment:",
- annotationCommentTitle: "Comment",
- annotationCommentPlaceholder: "Add a comment",
- annotationEdit: "Edit comment",
- annotationRemove: "Remove annotation",
- annotationReview: "Review annotations",
- annotationLocate: "Locate annotation",
- annotationRowLocation: "Original text unavailable; showing the source response",
- annotationChip: "{{count}} annotations",
- clearAnnotations: "Clear annotations",
- quoteSource: "Quoted from {{title}}",
- addToChat: "Add to chat",
- askInSideChat: "Ask in side chat",
- startSideChat: "Open side chat",
editMessage: "Edit and resend",
cancelEdit: "Cancel",
retryEdit: "Retry",
@@ -524,16 +506,6 @@ export const en = {
thinkingEnable: "Enable thinking",
untitledTask: "New task",
},
- sideChat: {
- parentBusy: "The main conversation is still replying. Wait for it to finish before starting this side chat.",
- readOnly: "This native Pi session is read-only right now.",
- title: "Side chat",
- sessionTitle: "Side chat: {{title}}",
- placeholder: "Ask a follow-up about this answer",
- empty: "Ask here to keep the main conversation unchanged.",
- addToMain: "Add to main chat",
- openAsSession: "Open as a conversation",
- },
session: {
renameTitle: "Rename task",
renameAction: "Rename task {{title}}",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index d6ca67969..459804de7 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -310,24 +310,6 @@ export const es = {
"openFile": "Abrir con aplicación predeterminada",
"retry": "Regenerar",
"forkResponse": "Rama de esta respuesta",
- "quote": "Citar",
- "annotate": "Añadir anotación",
- "annotationMarker": "Anotación {index}",
- "annotationSelectedText": "Texto seleccionado:",
- "annotationComment": "Comentario del usuario:",
- "annotationCommentTitle": "Comentario",
- "annotationCommentPlaceholder": "Añadir un comentario",
- "annotationEdit": "Editar comentario",
- "annotationRemove": "Quitar anotación",
- "annotationReview": "Revisar anotaciones",
- "annotationLocate": "Localizar anotación",
- "annotationRowLocation": "Texto original no disponible; se muestra la respuesta de origen",
- "annotationChip": "{{count}} anotaciones",
- "clearAnnotations": "Borrar anotaciones",
- "quoteSource": "Citado de {{title}}",
- "addToChat": "Añadir al chat",
- "askInSideChat": "Preguntar en el chat lateral",
- "startSideChat": "Abrir chat lateral",
"editMessage": "Editar y reenviar",
"cancelEdit": "Cancelar",
"retryEdit": "Reintentar",
@@ -517,16 +499,6 @@ export const es = {
"thinkingEnable": "Habilitar el pensamiento",
"untitledTask": "Nueva tarea"
},
- "sideChat": {
- parentBusy: "La conversación principal sigue respondiendo. Espera a que termine antes de iniciar este chat lateral.",
- readOnly: "Esta sesión nativa de Pi es de solo lectura en este momento.",
- "title": "Chat lateral",
- "sessionTitle": "Chat lateral: {{title}}",
- "placeholder": "Haga una pregunta de seguimiento sobre esta respuesta",
- "empty": "Pregunte aquí para no cambiar la conversación principal.",
- "addToMain": "Añadir al chat principal",
- "openAsSession": "Abrir como conversación"
- },
"session": {
"renameTitle": "Cambiar nombre de tarea",
"renameAction": "Cambiar nombre de tarea {{title}}",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index aef3cff6f..9d938a226 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -310,24 +310,6 @@ export const fr = {
"openFile": "Ouvrir avec l'application par défaut",
"retry": "Régénérer la branche",
"forkResponse": "à partir de cette réponse",
- "quote": "Citer",
- "annotate": "Ajouter une annotation",
- "annotationMarker": "Annotation {index}",
- "annotationSelectedText": "Texte sélectionné :",
- "annotationComment": "Commentaire de l'utilisateur :",
- "annotationCommentTitle": "Commentaire",
- "annotationCommentPlaceholder": "Ajouter un commentaire",
- "annotationEdit": "Modifier le commentaire",
- "annotationRemove": "Supprimer l'annotation",
- "annotationReview": "Examiner les annotations",
- "annotationLocate": "Localiser l’annotation",
- "annotationRowLocation": "Texte original indisponible ; affichage de la réponse source",
- "annotationChip": "{{count}} annotations",
- "clearAnnotations": "Effacer les annotations",
- "quoteSource": "Citation de {{title}}",
- "addToChat": "Ajouter au chat",
- "askInSideChat": "Demander dans le chat latéral",
- "startSideChat": "Ouvrir le chat latéral",
"editMessage": "Modifier et renvoyer",
"cancelEdit": "Annuler",
"retryEdit": "Réessayer",
@@ -517,16 +499,6 @@ export const fr = {
"thinkingEnable": "Activer la réflexion",
"untitledTask": "Nouvelle tâche"
},
- "sideChat": {
- parentBusy: "La conversation principale répond encore. Attendez la fin avant de démarrer cette discussion latérale.",
- readOnly: "Cette session Pi native est en lecture seule pour le moment.",
- "title": "Chat latéral",
- "sessionTitle": "Chat latéral : {{title}}",
- "placeholder": "Posez une question complémentaire sur cette réponse",
- "empty": "Posez votre question ici, sans modifier la conversation principale.",
- "addToMain": "Ajouter au chat principal",
- "openAsSession": "Ouvrir comme conversation"
- },
"session": {
"renameTitle": "Renommer la tâche",
"renameAction": "Renommer la tâche {{title}}",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 9cd491dc0..b9275a9e5 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -319,24 +319,6 @@ export const ko = {
openFile: "기본 애플리케이션으로 열기",
retry: "다시 생성",
forkResponse: "이 답변에서 브랜치 만들기",
- quote: "인용",
- annotate: "주석 추가",
- annotationMarker: "주석 {index}",
- annotationSelectedText: "선택한 텍스트:",
- annotationComment: "사용자 의견:",
- annotationCommentTitle: "댓글",
- annotationCommentPlaceholder: "댓글 추가",
- annotationEdit: "댓글 수정",
- annotationRemove: "주석 제거",
- annotationReview: "주석 검토",
- annotationLocate: "주석 위치 찾기",
- annotationRowLocation: "원문을 찾을 수 없어 원본 응답을 표시합니다",
- annotationChip: "주석 {{count}}개",
- clearAnnotations: "주석 지우기",
- quoteSource: "{{title}}에서 인용",
- addToChat: "채팅에 추가",
- askInSideChat: "사이드 채팅에서 질문",
- startSideChat: "사이드 채팅 열기",
editMessage: "편집 후 다시 보내기",
cancelEdit: "취소",
retryEdit: "다시 시도",
@@ -526,16 +508,6 @@ export const ko = {
thinkingEnable: "생각 기능 켜기",
untitledTask: "새 작업",
},
- sideChat: {
- parentBusy: "기본 대화가 응답 중입니다. 응답이 끝난 후 사이드 채팅을 시작하세요.",
- readOnly: "이 네이티브 Pi 세션은 현재 읽기 전용입니다.",
- title: "사이드 채팅",
- sessionTitle: "사이드 채팅: {{title}}",
- placeholder: "이 답변에 대해 이어서 질문하세요",
- empty: "여기에서 질문하면 기본 대화가 그대로 유지됩니다.",
- addToMain: "기본 대화에 추가",
- openAsSession: "대화로 열기",
- },
session: {
renameTitle: "작업 이름 바꾸기",
renameAction: "작업 이름 바꾸기 {{title}}",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 08c1e5803..75e6149a7 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -319,24 +319,6 @@ export const tr = {
openFile: "Varsayılan uygulamayla aç",
retry: "Yeniden oluştur",
forkResponse: "Bu yanıttan dal oluştur",
- quote: "Alıntıla",
- annotate: "Not ekle",
- annotationMarker: "Not {index}",
- annotationSelectedText: "Seçilen metin:",
- annotationComment: "Kullanıcı yorumu:",
- annotationCommentTitle: "Yorum",
- annotationCommentPlaceholder: "Yorum ekle",
- annotationEdit: "Yorumu düzenle",
- annotationRemove: "Notu kaldır",
- annotationReview: "Notları incele",
- annotationLocate: "Notu bul",
- annotationRowLocation: "Özgün metin bulunamadı; kaynak yanıt gösteriliyor",
- annotationChip: "{{count}} not",
- clearAnnotations: "Notları temizle",
- quoteSource: "{{title}} alıntısı",
- addToChat: "Sohbete ekle",
- askInSideChat: "Yan sohbette sor",
- startSideChat: "Yan sohbeti aç",
editMessage: "Düzenle ve yeniden gönder",
cancelEdit: "İptal",
retryEdit: "Yeniden dene",
@@ -526,16 +508,6 @@ export const tr = {
thinkingEnable: "Düşünmeyi aç",
untitledTask: "Yeni görev",
},
- sideChat: {
- parentBusy: "Ana sohbet hâlâ yanıt veriyor. Yan sohbeti başlatmadan önce bitmesini bekleyin.",
- readOnly: "Bu yerel Pi oturumu şu anda salt okunur.",
- title: "Yan sohbet",
- sessionTitle: "Yan sohbet: {{title}}",
- placeholder: "Bu yanıtla ilgili ek soru sorun",
- empty: "Buradan sorun, ana sohbet değişmeden kalır.",
- addToMain: "Ana sohbete ekle",
- openAsSession: "Sohbet olarak aç",
- },
session: {
renameTitle: "Görevi yeniden adlandır",
renameAction: "{{title}} görevini yeniden adlandır",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 0ec901bbb..994fdb9f5 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -312,24 +312,6 @@ export const zhCN = {
openFile: "用系统默认应用打开",
retry: "重新生成",
forkResponse: "从此回复创建分支",
- quote: "引用",
- annotate: "添加批注",
- annotationMarker: "批注 {index}",
- annotationSelectedText: "所选文本:",
- annotationComment: "用户评论:",
- annotationCommentTitle: "评论",
- annotationCommentPlaceholder: "添加评论",
- annotationEdit: "编辑评论",
- annotationRemove: "移除批注",
- annotationReview: "查看批注",
- annotationLocate: "定位批注",
- annotationRowLocation: "原选区已不可定位,显示来源回答",
- annotationChip: "{{count}} 条批注",
- clearAnnotations: "清除批注",
- quoteSource: "引用自 {{title}}",
- addToChat: "添加到对话",
- askInSideChat: "在侧边聊天中提问",
- startSideChat: "打开侧边聊天",
editMessage: "编辑并重新发送",
cancelEdit: "取消",
retryEdit: "重试",
@@ -522,16 +504,6 @@ export const zhCN = {
thinkingEnable: "开启思考",
untitledTask: "新建任务",
},
- sideChat: {
- parentBusy: "主会话仍在回复中,请等待回复结束后再发送侧边问题。",
- readOnly: "该原生 Pi 会话当前为只读状态。",
- title: "侧边聊天",
- sessionTitle: "侧边聊天:{{title}}",
- placeholder: "就这条回复继续追问",
- empty: "在这里追问,主对话不受影响。",
- addToMain: "加入主对话",
- openAsSession: "作为对话打开",
- },
session: {
renameTitle: "重命名任务",
renameAction: "重命名任务“{{title}}”",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index cb4fa1c17..638bf5a06 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -312,24 +312,6 @@ export const zhTW = {
openFile: "用系統預設應用開啟",
retry: "重新生成",
forkResponse: "從此回覆建立分支",
- quote: "引用",
- annotate: "新增批注",
- annotationMarker: "批註 {index}",
- annotationSelectedText: "選取文字:",
- annotationComment: "使用者評論:",
- annotationCommentTitle: "評論",
- annotationCommentPlaceholder: "新增評論",
- annotationEdit: "編輯評論",
- annotationRemove: "移除批註",
- annotationReview: "檢視批註",
- annotationLocate: "定位批註",
- annotationRowLocation: "原選區已無法定位,顯示來源回答",
- annotationChip: "{{count}} 則批註",
- clearAnnotations: "清除批註",
- quoteSource: "引用自 {{title}}",
- addToChat: "加入對話",
- askInSideChat: "在側邊聊天中提問",
- startSideChat: "開啟側邊聊天",
editMessage: "編輯並重新發送",
cancelEdit: "取消",
retryEdit: "重試",
@@ -522,16 +504,6 @@ export const zhTW = {
thinkingEnable: "開啟思考",
untitledTask: "新建任務",
},
- sideChat: {
- parentBusy: "主對話仍在回覆中,請等待回覆結束後再傳送側邊問題。",
- readOnly: "此原生 Pi 工作階段目前為唯讀狀態。",
- title: "側邊聊天",
- sessionTitle: "側邊聊天:{{title}}",
- placeholder: "就這則回覆繼續追問",
- empty: "在這裡追問,主對話不受影響。",
- addToMain: "加入主對話",
- openAsSession: "作為對話開啟",
- },
session: {
renameTitle: "重新命名任務",
renameAction: "重新命名任務“{{title}}”",
diff --git a/scripts/e2e-native-side-chat.mjs b/scripts/e2e-native-side-chat.mjs
deleted file mode 100644
index 10cb83163..000000000
--- a/scripts/e2e-native-side-chat.mjs
+++ /dev/null
@@ -1,423 +0,0 @@
-#!/usr/bin/env node
-/**
- * Runnable native Pi side-chat journey (E2E-SESSION-native-side-chat-fork-survives-close).
- *
- * Real pieces: the Electron main process hosts the real NativePiSessionService
- * and SDK SessionManager persistence over a temporary agent/session root with
- * an injected synthetic ModelRuntime (no network); the renderer bundle hosts
- * the real app store, session/queue/events slices, SideChatTab and
- * SearchDialog, talking over a real preload/ipcRenderer bridge with the same
- * channel names the app uses.
- *
- * Boundary note: this is not the production main process or the production
- * sidecar transport. The fork route is exercised at the same service call the
- * sidecar makes (`service.fork`), with the real renderer `api.forkSession`
- * contract above it.
- */
-import assert from "node:assert/strict";
-import { spawn } from "node:child_process";
-import { createRequire } from "node:module";
-import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import { resolveElectronBinary } from "./e2e/boot.mjs";
-
-const root = join(dirname(fileURLToPath(import.meta.url)), "..");
-const require = createRequire(join(root, "packages/agent-runtime/package.json"));
-const { build } = require("esbuild");
-// Offline installs skip Electron's download; CI/dev may point at an existing
-// signed app bundle through this override instead.
-const electronBinary =
- process.env.PI_DESKTOP_ELECTRON_BINARY ?? resolveElectronBinary(root).electronBinary;
-const temp = await mkdtemp(join(tmpdir(), "pi-native-side-chat-"));
-const project = join(temp, "fixture-project");
-
-const parentEntries = [
- { type: "session", version: 3, id: "probe-parent", timestamp: "2026-09-14T00:00:00.000Z", cwd: project },
- { type: "model_change", id: "m1", parentId: null, timestamp: "2026-09-14T00:00:00.500Z", provider: "test-provider", modelId: "test-model" },
- { type: "message", id: "u1", parentId: "m1", timestamp: "2026-09-14T00:00:01.000Z", message: { role: "user", content: [{ type: "text", text: "hello" }], timestamp: 1 } },
- { type: "message", id: "a1", parentId: "u1", timestamp: "2026-09-14T00:00:02.000Z", message: { role: "assistant", content: [{ type: "text", text: "first answer" }], provider: "test-provider", model: "test-model", stopReason: "stop", timestamp: 2 } },
- { type: "custom", id: "future", parentId: "a1", timestamp: "2026-09-14T00:00:03.000Z", customType: "opaque", data: { retained: true } },
-];
-const longEntries = [
- { type: "session", version: 3, id: "probe-long", timestamp: "2026-09-14T00:00:00.000Z", cwd: project },
- { type: "model_change", id: "m1", parentId: null, timestamp: "2026-09-14T00:00:00.500Z", provider: "test-provider", modelId: "test-model" },
-];
-{
- let parentId = "m1";
- for (let index = 0; index < 520; index += 1) {
- longEntries.push({
- type: "message",
- id: `u${index}`,
- parentId,
- timestamp: new Date(1_700_000_000_000 + index * 1_000).toISOString(),
- message: { role: "user", content: [{ type: "text", text: `row ${index}` }], timestamp: index },
- });
- parentId = `u${index}`;
- }
-}
-
-try {
- const agentDir = join(temp, "agent");
- const group = join(agentDir, "sessions", "--fixture-project--");
- await mkdir(group, { recursive: true });
- await mkdir(project);
- await writeFile(
- join(agentDir, "models.json"),
- JSON.stringify({
- providers: {
- "test-provider": {
- baseUrl: "http://127.0.0.1/unused",
- api: "openai-completions",
- models: [
- {
- id: "test-model",
- name: "Fixture",
- reasoning: false,
- input: ["text"],
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- contextWindow: 16000,
- maxTokens: 1000,
- },
- ],
- },
- },
- }),
- );
- await writeFile(
- join(agentDir, "auth.json"),
- JSON.stringify({ "test-provider": { type: "api_key", key: "synthetic-probe-key" } }),
- );
- await writeFile(
- join(agentDir, "settings.json"),
- JSON.stringify({ retry: { enabled: false }, compaction: { enabled: false } }),
- );
- const parentFile = join(group, "probe-parent.jsonl");
- await writeFile(parentFile, `${parentEntries.map((entry) => JSON.stringify(entry)).join("\n")}\n`);
- await writeFile(join(group, "probe-long.jsonl"), `${longEntries.map((entry) => JSON.stringify(entry)).join("\n")}\n`);
-
- await build({
- entryPoints: [join(root, "scripts/e2e/native-side-chat.tsx")],
- outfile: join(temp, "renderer.js"),
- bundle: true,
- platform: "browser",
- format: "iife",
- jsx: "automatic",
- define: { "process.env.NODE_ENV": '"production"' },
- loader: { ".css": "empty" },
- alias: {
- "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
- "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),
- react: join(root, "apps/desktop/node_modules/react"),
- "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
- },
- nodePaths: [join(root, "node_modules"), join(root, "apps/desktop/node_modules")],
- });
- await writeFile(
- join(temp, "index.html"),
- '<!doctype html><meta charset="utf-8"><title>Native side chat probe</title><script src="renderer.js"></script>',
- );
- await writeFile(
- join(temp, "preload.cjs"),
- `
-const { contextBridge, ipcRenderer } = require("electron");
-contextBridge.exposeInMainWorld("piDesktop", {
- invoke: (channel, ...args) => ipcRenderer.invoke("probe.invoke", channel, args),
- on: (channel, listener) => {
- const wrapped = (_event, payload) => listener(payload);
- ipcRenderer.on(channel, wrapped);
- return () => ipcRenderer.removeListener(channel, wrapped);
- },
- channels: {},
- platform: process.platform,
- locale: "en",
-});
-`,
- );
- await writeFile(
- join(temp, "fixture.json"),
- JSON.stringify({
- agentDir,
- sessionRoot: join(agentDir, "sessions"),
- parentFile,
- agentRuntimeEntry: join(root, "packages/agent-runtime/dist/native-pi-session.js"),
- leaseEntry: join(root, "packages/agent-runtime/dist/native-pi-session-lease.js"),
- piAiEntry: join(root, "packages/agent-runtime/node_modules/@earendil-works/pi-ai/dist/index.js"),
- piCodingAgentEntry: join(root, "packages/agent-runtime/node_modules/@earendil-works/pi-coding-agent/dist/index.js"),
- }),
- );
- await writeFile(
- join(temp, "main.cjs"),
- `
-const { app, BrowserWindow, ipcMain } = require("electron");
-const path = require("node:path");
-const fs = require("node:fs");
-const crypto = require("node:crypto");
-const { pathToFileURL } = require("node:url");
-
-app.setPath("userData", path.join(__dirname, "profile"));
-app.commandLine.appendSwitch("host-resolver-rules", "MAP * 0.0.0.0");
-
-const FIXTURE = JSON.parse(fs.readFileSync(path.join(__dirname, "fixture.json"), "utf8"));
-const sha256 = (value) => crypto.createHash("sha256").update(value).digest("hex");
-const parentBytes = fs.readFileSync(FIXTURE.parentFile);
-const initialHash = sha256(parentBytes);
-
-function assistantMessage(stopReason, text) {
- return {
- role: "assistant",
- content: [{ type: "text", text }],
- api: "openai-completions",
- provider: "test-provider",
- model: "test-model",
- stopReason,
- timestamp: Date.now(),
- usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
- };
-}
-
-function chunkedStream(piAi, signal) {
- const stream = piAi.createAssistantMessageEventStream();
- const text = "fixture reply";
- const pieces = [text.slice(0, 5), text.slice(5, 8), text.slice(8)];
- let index = 0;
- let settled = false;
- const abortNow = () => {
- if (settled) return;
- settled = true;
- clearInterval(timer);
- const text = pieces.slice(0, index).join("");
- const message = {
- ...assistantMessage("aborted", text),
- content: text ? [{ type: "text", text }] : [],
- };
- stream.push({ type: "error", reason: "aborted", error: message });
- stream.end(message);
- };
- const timer = setInterval(() => {
- if (signal?.aborted) return abortNow();
- if (index === pieces.length) {
- settled = true;
- clearInterval(timer);
- const message = assistantMessage("stop", text);
- stream.push({ type: "done", reason: "stop", message });
- stream.end(message);
- return;
- }
- if (index === 0) stream.push({ type: "start", partial: assistantMessage("stop", "") });
- const partial = assistantMessage("stop", pieces.slice(0, index + 1).join(""));
- stream.push({ type: "text_delta", contentIndex: 0, delta: pieces[index], partial });
- index += 1;
- }, 180);
- signal?.addEventListener("abort", abortNow);
- return stream;
-}
-
-async function main() {
- const { NativePiSessionService } = await import(pathToFileURL(FIXTURE.agentRuntimeEntry).href);
- const { acquireNativePiSessionLease } = await import(pathToFileURL(FIXTURE.leaseEntry).href);
- const piAi = await import(pathToFileURL(FIXTURE.piAiEntry).href);
- const { ModelRuntime } = await import(pathToFileURL(FIXTURE.piCodingAgentEntry).href);
- // Bounded synthetic provider: the service still initializes the real offline
- // ModelRuntime from the temporary agent directory; only the streaming call is
- // replaced with a chunked synthetic response.
- globalThis.fetch = () => Promise.reject(new Error("Network forbidden in native side-chat probe"));
- ModelRuntime.prototype.streamSimple = function streamSimple(_model, _context, options) {
- return chunkedStream(piAi, options?.signal);
- };
- let service = new NativePiSessionService({
- agentDir: FIXTURE.agentDir,
- sessionRoot: FIXTURE.sessionRoot,
- });
- let promptCount = 0;
- const window = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: path.join(__dirname, "preload.cjs"),
- sandbox: true,
- contextIsolation: true,
- nodeIntegration: false,
- },
- });
- const channels = {
- "pi-desktop/session/list": async () => ({ sessions: await service.list() }),
- "pi-desktop/session/search": async (_event, input) =>
- service.search(String(input?.query ?? "")),
- "pi-desktop/session/get": async (_event, input) => ({
- session: service.detail(String(input.id), {
- messageBefore: input.messageBefore,
- messageAround: input.messageAround,
- messageLimit: input.messageLimit,
- contentLimit: input.contentLimit,
- }),
- }),
- "pi-desktop/session/fork": async (_event, input) => ({
- session: service.fork({
- id: String(input.sessionId),
- title: typeof input.title === "string" ? input.title : undefined,
- throughMessageId: typeof input.throughMessageId === "string" ? input.throughMessageId : undefined,
- }),
- }),
- "pi-desktop/agent/prompt": async (_event, request) => {
- const content = String(request.content ?? "");
- promptCount += 1;
- return service.prompt(
- String(request.sessionId),
- content,
- (envelope) => window.webContents.send("pi-desktop/agent/event/message", envelope),
- typeof request.messageId === "string" ? request.messageId : undefined,
- );
- },
- "pi-desktop/agent/abort": async (_event, input) => {
- await service.abort(String(input.sessionId));
- return { ok: true };
- },
- };
- const probes = {
- "probe.sessionCount": async () => ({ count: (await service.list()).length }),
- "probe.detail": async (_event, input) => ({ session: service.detail(String(input.id)) }),
- "probe.promptCount": async () => ({ count: promptCount }),
- "probe.restartService": async () => {
- // Production-equivalent restart: dispose live runtimes and construct a
- // fresh service that must rediscover everything from the JSONL files.
- service.disposeAll();
- service = new NativePiSessionService({
- agentDir: FIXTURE.agentDir,
- sessionRoot: FIXTURE.sessionRoot,
- });
- return { restarted: true };
- },
- "probe.parentBytes": async () => ({
- initial: initialHash,
- hash: sha256(fs.readFileSync(FIXTURE.parentFile)),
- }),
- "probe.forkBusy": async () => {
- // The long parent has no owned runtime, so a live foreign lease must
- // refuse the fork. (An owned idle runtime keeps its own lease by design.)
- const summaries = await service.list();
- const long = summaries.find((session) => session.messageCount === 520);
- const longFile = fs
- .readdirSync(path.join(FIXTURE.sessionRoot, "--fixture-project--"))
- .find((name) => name.startsWith("probe-long"));
- const lease = acquireNativePiSessionLease(
- path.join(FIXTURE.sessionRoot, "--fixture-project--", longFile),
- );
- try {
- service.fork({ id: long.id, title: "blocked" });
- return { code: "NONE" };
- } catch (error) {
- return { code: error?.errorCode ?? error?.code ?? "UNKNOWN" };
- } finally {
- lease.release();
- }
- },
- "probe.forkLong": async () => {
- const summaries = await service.list();
- const long = summaries.find((session) => session.messageCount === 520);
- const child = service.fork({ id: long.id, title: "Long child" });
- return {
- count: child.messages.length,
- hasMoreBefore: child.hasMoreBefore,
- messageStart: child.messageStart,
- };
- },
- };
- ipcMain.handle("probe.invoke", async (event, channel, args) => {
- try {
- const handler = channels[channel] ?? probes[channel];
- if (!handler) throw Object.assign(new Error("probe channel not implemented"), { errorCode: "PROBE_UNIMPLEMENTED" });
- const data = await handler(event, ...(args ?? []));
- return { ok: true, data };
- } catch (error) {
- return {
- ok: false,
- error: {
- code: error?.errorCode ?? error?.code ?? "PROBE_ERROR",
- message: error?.message ?? String(error),
- },
- };
- }
- });
- window.webContents.session.webRequest.onBeforeRequest(
- { urls: ["http://*/*", "https://*/*"] },
- (_details, callback) => callback({ cancel: true }),
- );
- await window.loadFile(path.join(__dirname, "index.html"));
- const phase1 = await window.webContents.executeJavaScript(
- "globalThis.nativeSideChatProbePhase1()",
- );
- let result = phase1;
- if (phase1?.ok && phase1.phase2) {
- await probes["probe.restartService"]();
- const loaded = new Promise((resolve) => window.webContents.once("did-finish-load", resolve));
- window.webContents.reload();
- await loaded;
- const phase2 = await window.webContents.executeJavaScript(
- "globalThis.nativeSideChatProbePhase2(" + JSON.stringify(phase1.phase2) + ")",
- );
- result = {
- ok: Boolean(phase2?.ok),
- error: phase2?.error,
- checks: [...(phase1.checks ?? []), ...(phase2?.checks ?? [])],
- };
- }
- console.log("NATIVE_SIDE_CHAT_PROBE " + JSON.stringify(result));
- service.disposeAll();
- app.exit(result?.ok ? 0 : 1);
-}
-
-app.whenReady().then(main).catch((error) => {
- console.error("NATIVE_SIDE_CHAT_PROBE " + JSON.stringify({ ok: false, error: String(error?.stack ?? error) }));
- app.exit(1);
-});
-`,
- );
-
- // Standalone isolation: a temporary HOME/USERPROFILE so SDK default lookups
- // (getAgentDir, trust-manager skills) cannot read the real profile, plus a
- // scrub of inherited native session selectors for the probe process only.
- const env = {
- ...process.env,
- HOME: temp,
- USERPROFILE: temp,
- PI_OFFLINE: "1",
- PI_CODING_AGENT_DIR: agentDir,
- PI_CODING_AGENT_SESSION_DIR: join(agentDir, "sessions"),
- };
- delete env.ELECTRON_RUN_AS_NODE;
- delete env.PI_SESSION_FILE;
- delete env.PI_SESSION_ID;
- const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
- let output = "";
- for (const stream of [child.stdout, child.stderr]) {
- stream.on("data", (data) => {
- output += data;
- });
- }
- const timeout = setTimeout(() => child.kill("SIGKILL"), 90_000);
- let code;
- try {
- code = await new Promise((resolve, reject) => {
- child.once("error", reject);
- child.once("close", resolve);
- });
- } finally {
- clearTimeout(timeout);
- }
- const line = output
- .split(/\r?\n/)
- .find((candidate) => candidate.startsWith("NATIVE_SIDE_CHAT_PROBE "));
- assert(line, `probe returned no result (exit=${code}): ${output.slice(-4000)}`);
- const result = JSON.parse(line.slice("NATIVE_SIDE_CHAT_PROBE ".length));
- if (result.checks) {
- for (const check of result.checks) {
- console.log(`${check.ok ? "ok" : "FAIL"} - ${check.name}${check.detail ? ` :: ${check.detail}` : ""}`);
- }
- }
- assert.equal(result.ok, true, output.slice(-6000));
- assert.equal(code, 0, output.slice(-6000));
- console.log("NATIVE_SIDE_CHAT_PROBE PASS");
-} finally {
- await rm(temp, { recursive: true, force: true });
-}
diff --git a/scripts/e2e/native-side-chat.tsx b/scripts/e2e/native-side-chat.tsx
deleted file mode 100644
index 3fa8ac02b..000000000
--- a/scripts/e2e/native-side-chat.tsx
+++ /dev/null
@@ -1,561 +0,0 @@
-/**
- * Renderer half of the runnable native side-chat journey
- * (`pnpm test:e2e:native-side-chat`).
- *
- * Drives the real app store, real session/queue/events slices, the real
- * SideChatTab panel and the real SearchDialog over the real preload bridge.
- * The Electron main process hosts the real NativePiSessionService with the
- * real offline ModelRuntime and a bounded synthetic chunked stream; phase 2
- * runs after the main process rebuilds the service and the window reloads,
- * so a persisted child must be rediscovered from disk by a fresh renderer.
- */
-import { createRoot } from "react-dom/client";
-import i18n from "i18next";
-import { initReactI18next } from "react-i18next";
-import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
-import { useAppStore } from "../../apps/desktop/src/stores/app-store";
-import { api } from "../../apps/desktop/src/lib/api";
-import {
- draftKeyForSession,
- readComposerDraft,
- writeComposerDraft,
-} from "../../apps/desktop/src/lib/composer-draft-cache";
-import { SideChatTab } from "../../apps/desktop/src/components/workpanel/SideChatTab";
-import { SearchDialog } from "../../apps/desktop/src/components/SearchDialog";
-
-// The production renderer initializes i18n in main.tsx; this probe renders the
-// real components, so it must provide the same locale resources.
-void i18n.use(initReactI18next).init({
- lng: "en",
- fallbackLng: "en",
- resources: Object.fromEntries(
- Object.entries(catalogs).map(([lng, catalog]) => [
- lng,
- { translation: flattenCatalog(catalog as unknown as Record<string, unknown>) },
- ]),
- ),
- interpolation: { escapeValue: false },
-});
-
-type Check = { name: string; ok: boolean; detail?: string };
-type ProbeResult = { ok: boolean; checks: Check[]; error?: string };
-
-const bridge = (window as any).piDesktop;
-
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
-
-async function until<T>(
- fn: () => T | undefined | false | null,
- timeout = 25_000,
- label = "probe",
-): Promise<T> {
- const end = Date.now() + timeout;
- while (Date.now() < end) {
- const value = fn();
- if (value) return value as T;
- await sleep(40);
- }
- throw new Error(`${label} timeout after ${timeout}ms`);
-}
-
-function setValue(
- element: HTMLTextAreaElement | HTMLInputElement,
- value: string,
-): void {
- const prototype =
- element instanceof HTMLTextAreaElement
- ? HTMLTextAreaElement.prototype
- : HTMLInputElement.prototype;
- Object.getOwnPropertyDescriptor(prototype, "value")!.set!.call(element, value);
- element.dispatchEvent(new Event("input", { bubbles: true }));
-}
-
-function createChecks() {
- const checks: Check[] = [];
- const check = (name: string, ok: boolean, detail?: string) => {
- checks.push({ name, ok: Boolean(ok), ...(detail ? { detail } : {}) });
- if (!ok) throw new Error(name);
- };
- return { checks, check };
-}
-
-const panelHost = () => document.querySelector(".side-chat");
-const composer = () => document.querySelector("form.side-chat-composer") as HTMLFormElement;
-const textarea = () => document.querySelector("textarea.side-chat-input") as HTMLTextAreaElement;
-const sideChatRow = (title: string) =>
- Array.from(document.querySelectorAll<HTMLButtonElement>(
- '.search-dialog button[role="option"][title]',
- )).find((row) => row.title === title);
-
-type Phase2Input = {
- childId: string;
- parentId: string;
- projectPath: string;
- expectedIds: string[];
- abortedId: string;
- abortedPartial: string;
- parentHashBefore: string;
-};
-
-(globalThis as any).nativeSideChatProbePhase1 = async (): Promise<ProbeResult> => {
- const { checks, check } = createChecks();
- const rootElements: HTMLElement[] = [];
- const offAgentEvents = api.onAgentEvent((envelope) =>
- useAppStore.getState().handleAgentEvent(envelope),
- );
- try {
- const { sessions } = await api.listSessions();
- const parent = sessions.find(
- (session) => session.source === "pi-native" && String(session.title) === "hello",
- );
- check("native parent listed", Boolean(parent), JSON.stringify(sessions.map((s) => s.title)));
- const parentDetail = await api.getSession(parent!.id);
- check(
- "parent transcript loaded",
- (parentDetail.session?.messages?.length ?? 0) >= 2,
- String(parentDetail.session?.messages?.length),
- );
- useAppStore.setState({
- sessions,
- activeSessionId: parent!.id,
- activeProjectPath: parent!.projectPath,
- workspace: parent!.projectPath
- ? { path: parent!.projectPath, name: "fixture-project" }
- : null,
- messages: parentDetail.session!.messages!,
- page: "chat",
- runningSessions: {},
- sideChats: {},
- sideChatTranscripts: {},
- toasts: [],
- queuedPrompts: {},
- } as any);
-
- // The main conversation must survive every child operation untouched.
- const mainMessages = useAppStore.getState().messages;
- const mainNav = {
- page: useAppStore.getState().page,
- index: useAppStore.getState().navIndex,
- stack: JSON.stringify(useAppStore.getState().navStack),
- };
- const mainDraftKey = draftKeyForSession(parent!.id);
- writeComposerDraft(mainDraftKey, {
- text: "main draft sentinel",
- fileReferences: [],
- });
-
- const queueCalls: unknown[] = [];
- const originalQueuePrompt = api.queuePrompt;
- api.queuePrompt = (async (...args: unknown[]) => {
- queueCalls.push(args);
- throw new Error("native child must not use the Desktop queue");
- }) as typeof api.queuePrompt;
-
- // Concurrent clicks on one anchor share one open through the real slice.
- const sessionCountBefore = (await bridge.invoke("probe.sessionCount")).data.count;
- const [draftId, secondChildId] = await Promise.all([
- useAppStore.getState().openSideChat("a1"),
- useAppStore.getState().openSideChat("a1"),
- ]);
- let childId = draftId;
- check("concurrent open shares one draft", Boolean(draftId) && draftId === secondChildId, String(draftId));
- const sessionCountAfter = (await bridge.invoke("probe.sessionCount")).data.count;
- check(
- "opening does not publish a child file",
- sessionCountAfter === sessionCountBefore,
- `${sessionCountBefore} -> ${sessionCountAfter}`,
- );
- const rows = () =>
- useAppStore.getState().sideChatTranscripts[childId!] ?? [];
- check("anchored history seeded whole", rows().length === 2, JSON.stringify(rows().map((r) => r.id)));
- const childSummary = () =>
- useAppStore.getState().sessions.find((session) => session.id === childId);
- check("draft is absent from session list", !childSummary());
-
- // Closing an unsubmitted first-user draft leaves no session file.
- const firstUserId = await useAppStore.getState().openSideChat("u1", "quoted question");
- check("selection prefills without sending", useAppStore.getState().sideChats[firstUserId!]?.draft === "> quoted question\n\n");
- useAppStore.getState().closeSideChat(firstUserId!);
- check("unsent draft stays absent after close", (await bridge.invoke("probe.sessionCount")).data.count === sessionCountBefore);
- await useAppStore.getState().openSideChat("a1");
-
- const host = document.createElement("div");
- document.body.appendChild(host);
- rootElements.push(host);
- function ActiveSideChat() {
- const id = useAppStore((state) => state.workPanelTabs.find((tab) => tab.kind === "sidechat")?.resource);
- return id ? <SideChatTab sessionId={id} /> : null;
- }
- createRoot(host).render(<ActiveSideChat />);
- await until(() => panelHost(), 25_000, "panel");
- await until(
- () => document.querySelector('.side-chat-thread')?.textContent?.includes('first answer'),
- 25_000,
- "panel history",
- );
- check("panel paints the anchored answer", Boolean(
- document.querySelector('.side-chat-thread')?.textContent?.includes('first answer'),
- ));
-
- // The draft gate follows the parent live, before any child exists.
- setValue(textarea(), "guarded question");
- useAppStore.setState({ runningSessions: { [parent!.id]: true } });
- await until(() => composer().querySelector<HTMLButtonElement>('button[type="submit"]')?.disabled, 5_000, "busy draft disabled");
- check("busy parent explanation visible", Boolean(panelHost()?.textContent?.includes("main conversation is still replying")));
- check("busy parent creates no child", (await bridge.invoke("probe.sessionCount")).data.count === sessionCountBefore);
- useAppStore.setState({ runningSessions: {}, sessions: useAppStore.getState().sessions.map((row) => row.id === parent!.id ? { ...row, readOnlyReason: "provider-unavailable" } : row) });
- await until(() => panelHost()?.textContent?.includes("read-only"), 5_000, "read-only draft explanation");
- check("read-only parent disables Send", Boolean(composer().querySelector<HTMLButtonElement>('button[type="submit"]')?.disabled));
- check("read-only parent creates no child", (await bridge.invoke("probe.sessionCount")).data.count === sessionCountBefore);
- useAppStore.setState({ sessions: useAppStore.getState().sessions.map((row) => row.id === parent!.id ? { ...row, readOnlyReason: undefined } : row) });
- await until(() => !composer().querySelector<HTMLButtonElement>('button[type="submit"]')?.disabled, 5_000, "draft Send recovers");
- check("guard changes preserve draft", textarea().value === "guarded question");
-
- setValue(textarea(), "probe question");
- composer().dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
- childId = await until(() => Object.values(useAppStore.getState().sideChats).find(
- (entry) => entry.anchorMessageId === "a1" && !entry.pending,
- )?.sessionId, 25_000, "first Send creates child") as string;
- check("first Send creates exactly one child", (await bridge.invoke("probe.sessionCount")).data.count === sessionCountBefore + 1);
- check("child title is the side-chat title", String(childSummary()?.title).startsWith("Side chat"));
- const searchTitle = childSummary()!.title;
- const sendOutcome = await until(() => {
- if (rows().some((row) => row.status === "streaming" && String(row.content).length > 0)) {
- return "streaming";
- }
- const failed =
- rows().some((row) => row.status === "error") ||
- useAppStore.getState().toasts.length > 0;
- return failed
- ? `failed:${JSON.stringify({
- rows: rows().map((row) => [row.role, row.status, row.error?.message]),
- toasts: useAppStore.getState().toasts.map((toast) => toast.message),
- })}`
- : false;
- }, 25_000, "send");
- check("reply streams progressively into the panel", sendOutcome === "streaming", sendOutcome);
- const streamingId = rows().find((row) => row.status === "streaming")!.id;
- const paintedWhileStreaming = await until(
- () => rows().some((row) => row.id === streamingId && row.status === 'streaming') &&
- Boolean(document.querySelector('.side-chat-thread')?.textContent?.includes('fixtu')),
- 10_000,
- 'partial reply DOM',
- );
- check('partial reply paints before settlement', paintedWhileStreaming);
-
- // A send while the child is running is rejected before the Desktop queue
- // and never overwrites text typed after the failed submission.
- setValue(textarea(), "typed while running");
- composer().dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
- await until(
- () => useAppStore.getState().toasts.some((toast) => /still replying/.test(toast.message)),
- 10_000,
- "busy toast",
- );
- await sleep(120);
- check("busy send keeps the newer draft", textarea().value === "typed while running", textarea().value);
- check("native send never used the Desktop queue", queueCalls.length === 0);
-
- await until(
- () => rows().some((row) => row.role === "assistant" && row.status === "complete" && row.id !== streamingId),
- 25_000,
- "reply completion",
- );
- await until(() => !rows().some((row) => row.status === "streaming"), 10_000, "streaming settle");
- const assistantRows = rows().filter((row) => row.role === "assistant");
- check(
- "provisional row re-keyed to exactly one durable row",
- assistantRows.length === 2 && !assistantRows.some((row) => row.id === streamingId),
- JSON.stringify(rows().map((row) => [row.role, row.id, row.status])),
- );
- check(
- "durable user acknowledgement",
- rows().filter((row) => row.role === "user").length === 2,
- JSON.stringify(rows().map((row) => [row.role, row.id])),
- );
- const replyRow = assistantRows.at(-1)!;
- const questionRow = rows().find((row) => row.role === "user" && String(row.content).includes("probe question"))!;
- const parentBytes = await bridge.invoke("probe.parentBytes");
- check(
- "parent bytes unchanged after fork and turn",
- parentBytes.ok && parentBytes.data.hash === parentBytes.data.initial,
- JSON.stringify(parentBytes),
- );
-
- // Stop: the synthetic stream keeps the partial text it already produced,
- // so the aborted durable row must persist that text exactly once.
- setValue(textarea(), "probe stop");
- composer().dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
- await until(
- () => rows().some((row) => row.status === "streaming" && String(row.content).length > 0),
- 25_000,
- "stop stream",
- );
- await useAppStore.getState().abortSession(childId!);
- await until(() => !rows().some((row) => row.status === "streaming"), 15_000, "stop settle");
- check(
- "stop keeps the durable user row",
- rows().some((row) => row.role === "user" && String(row.content).includes("probe stop")),
- JSON.stringify(rows().map((row) => [row.role, row.content])),
- );
- const abortedRow = rows().find((row) => row.status === "aborted");
- check(
- "abort keeps the generated partial text",
- Boolean(abortedRow) && String(abortedRow!.content).trim().length > 0,
- JSON.stringify(rows().map((row) => [row.role, row.status, row.content])),
- );
- check(
- "aborted partial appears exactly once",
- rows().filter((row) => row.id === abortedRow!.id).length === 1,
- String(abortedRow!.id),
- );
- const stopRow = rows().find(
- (row) => row.role === "user" && String(row.content).includes("probe stop"),
- )!;
-
- // Delayed preflight failure: newer text typed while the send is awaiting
- // the transport must survive the failure restore.
- const originalPrompt = api.prompt;
- useAppStore.setState({ toasts: [] });
- let rejectionFinished = false;
- api.prompt = (async () => {
- await sleep(400);
- rejectionFinished = true;
- throw Object.assign(new Error("delayed preflight failure"), {
- code: "NATIVE_PI_PROVIDER_UNAVAILABLE",
- });
- }) as typeof api.prompt;
- setValue(textarea(), "first attempt");
- composer().dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
- await sleep(120);
- setValue(textarea(), "typed during await");
- await until(
- () => rejectionFinished &&
- useAppStore.getState().toasts.some((toast) => toast.message === 'delayed preflight failure'),
- 10_000,
- "delayed failure",
- );
- await sleep(120);
- check(
- "newer text typed during the await survives the failure",
- textarea().value === "typed during await",
- textarea().value,
- );
- api.prompt = originalPrompt;
-
- // Scoped global search: the child's own row, a negative query, and the
- // project label, not a document-wide substring.
- const searchHost = document.createElement("div");
- document.body.appendChild(searchHost);
- rootElements.push(searchHost);
- createRoot(searchHost).render(<SearchDialog open onClose={() => undefined} />);
- const searchInput = await until(
- () => document.querySelector("input.search-input") as HTMLInputElement | null,
- 10_000,
- "search input",
- );
- setValue(searchInput!, "zzz");
- await until(() => searchInput.value === 'zzz' && !sideChatRow(searchTitle), 10_000, "negative query");
- check("negative query removes the child row", !sideChatRow(searchTitle));
- setValue(searchInput!, "side chat");
- await until(() => sideChatRow(searchTitle), 10_000, "title search");
- check("title search finds the scoped child row", Boolean(sideChatRow(searchTitle)));
- setValue(searchInput!, "zzz-again");
- await until(() => !sideChatRow(searchTitle), 10_000, "second negative query");
- setValue(searchInput!, "fixture-project");
- await until(() => sideChatRow(searchTitle), 10_000, "project search");
- check("project search finds the scoped child row", Boolean(sideChatRow(searchTitle)));
-
- // Main conversation, navigation and draft are untouched by child activity,
- // and close only drops the panel registration.
- check("main session still active", useAppStore.getState().activeSessionId === parent!.id);
- check("main transcript untouched", useAppStore.getState().messages === mainMessages);
- check(
- "main navigation untouched",
- useAppStore.getState().page === mainNav.page &&
- useAppStore.getState().navIndex === mainNav.index &&
- JSON.stringify(useAppStore.getState().navStack) === mainNav.stack,
- JSON.stringify(mainNav),
- );
- check(
- "main composer draft untouched",
- readComposerDraft(mainDraftKey)?.text === "main draft sentinel",
- JSON.stringify(readComposerDraft(mainDraftKey)),
- );
-
- useAppStore.getState().closeSideChat(childId!);
- check("close removes the panel registration", !useAppStore.getState().sideChats[childId!]);
- await useAppStore.getState().refreshSessions();
- const listedChild = () =>
- useAppStore.getState().sessions.find((session) => session.id === childId);
- check("child stays in the session list after close", Boolean(listedChild()));
- check(
- "child keeps its project label",
- listedChild()?.projectPath === parent!.projectPath,
- String(listedChild()?.projectPath),
- );
-
- // Wrong cases against the real service: foreign lease and long branch.
- const busy = await bridge.invoke("probe.forkBusy");
- check(
- "foreign lease blocks fork",
- busy.ok && busy.data.code === "NATIVE_PI_SESSION_BUSY",
- JSON.stringify(busy),
- );
- const long = await bridge.invoke("probe.forkLong");
- check(
- "long branch child returns the whole transcript",
- long.ok &&
- long.data.count === 520 &&
- long.data.hasMoreBefore === false &&
- long.data.messageStart === 0,
- JSON.stringify(long),
- );
-
- const freshParentBytes = await bridge.invoke("probe.parentBytes");
- check('parent bytes unchanged after every phase-one operation',
- freshParentBytes.ok && freshParentBytes.data.hash === parentBytes.data.initial,
- );
- const expectedIds = [
- "u1",
- "a1",
- questionRow.id,
- replyRow.id,
- stopRow.id,
- abortedRow!.id,
- ];
- api.queuePrompt = originalQueuePrompt;
- return {
- ok: true,
- checks,
- phase2: {
- childId: childId!,
- parentId: parent!.id,
- projectPath: parent!.projectPath,
- expectedIds,
- abortedId: abortedRow!.id,
- abortedPartial: String(abortedRow!.content),
- parentHashBefore: parentBytes.data.initial,
- },
- } as ProbeResult & { phase2: Phase2Input };
- } catch (error) {
- return {
- ok: false,
- error: error instanceof Error ? (error.stack ?? error.message) : String(error),
- checks,
- };
- } finally {
- offAgentEvents();
- for (const element of rootElements) element.remove();
- }
-};
-
-(globalThis as any).nativeSideChatProbePhase2 = async (
- input: Phase2Input,
-): Promise<ProbeResult> => {
- const { checks, check } = createChecks();
- const offAgentEvents = api.onAgentEvent((envelope) =>
- useAppStore.getState().handleAgentEvent(envelope),
- );
- try {
- // A fresh renderer after a service restart and a window reload: the child
- // must be rediscovered from disk, not from any in-memory copy.
- const { sessions } = await api.listSessions();
- const child = sessions.find((session) => session.id === input.childId);
- check(
- "fresh renderer lists the durable child after service restart",
- Boolean(child),
- JSON.stringify(sessions.map((session) => [session.id, session.title]).slice(0, 6)),
- );
- check(
- "fresh child keeps title and project",
- String(child!.title).startsWith("Side chat") && child!.projectPath === input.projectPath,
- JSON.stringify([child!.title, child!.projectPath]),
- );
- useAppStore.setState({
- sessions,
- activeSessionId: input.parentId,
- activeProjectPath: input.projectPath,
- workspace: { path: input.projectPath, name: "fixture-project" },
- messages: [],
- retainedTranscripts: {},
- sideChatTranscripts: {},
- sideChats: {},
- toasts: [],
- runningSessions: {},
- } as any);
- await useAppStore.getState().selectSession(input.childId);
- await until(
- () =>
- useAppStore.getState().activeSessionId === input.childId &&
- !useAppStore.getState().selectingSessionId,
- 25_000,
- "reopen selection",
- );
- const messages = useAppStore.getState().messages;
- check('fresh history has exactly the durable rows in order',
- JSON.stringify(messages.map((message) => message.id)) === JSON.stringify(input.expectedIds),
- );
- for (const id of input.expectedIds) {
- check(
- `durable row ${id} loads exactly once`,
- messages.filter((message) => message.id === id).length === 1,
- JSON.stringify(messages.map((message) => [message.role, message.id, message.status])),
- );
- }
- check("reopen has no provisional row", !messages.some((message) => message.status === "streaming"));
- const aborted = messages.filter((message) => message.id === input.abortedId);
- check(
- "aborted partial persisted once after reopen",
- aborted.length === 1 && String(aborted[0].content) === input.abortedPartial,
- JSON.stringify(aborted.map((message) => message.content)),
- );
-
- // Continue the reopened child through the real prompt path.
- const before = await api.getSession(input.childId);
- const accepted = await useAppStore.getState().sendPrompt(
- "post-restart continue",
- { text: "post-restart continue", fileReferences: [] },
- input.childId,
- );
- check("continue accepted after restart", accepted === true, String(accepted));
- const assistantBefore =
- before.session?.messages?.filter((row: any) => row.role === "assistant") ?? [];
- await until(() => {
- const state = useAppStore.getState();
- const running = state.runningSessions[input.childId] === true;
- const assistantCount = state.messages.filter((row) => row.role === "assistant").length;
- const failed =
- state.messages.some((row) => row.status === "error") || state.toasts.length > 0;
- return !running && (assistantCount > assistantBefore.length || failed);
- }, 25_000, "continued reply");
- await until(
- () => !useAppStore.getState().messages.some((row) => row.status === "streaming"),
- 10_000,
- "continue settle",
- );
- const continued = useAppStore.getState().messages;
- const assistantAfter = continued.filter((row) => row.role === "assistant");
- check(
- "continued reply is one new durable assistant row",
- assistantAfter.length === assistantBefore.length + 1 &&
- !continued.some((row) => row.status === "streaming" || row.status === "error"),
- JSON.stringify(continued.map((row) => [row.role, row.id, row.status])),
- );
- const parentBytes = await bridge.invoke("probe.parentBytes");
- check(
- "parent bytes still unchanged after restart and continue",
- parentBytes.ok && parentBytes.data.hash === input.parentHashBefore,
- JSON.stringify(parentBytes),
- );
- return { ok: true, checks };
- } catch (error) {
- return {
- ok: false,
- error: error instanceof Error ? (error.stack ?? error.message) : String(error),
- checks,
- };
- } finally {
- offAgentEvents();
- }
-};