Files
t3code/apps/web/src/lib/terminalContext.test.ts
T
Aiden Bai 17fb0e4a9a feat(preview): element-pick attachments + sandboxed picker preload
Adds an in-page element picker to the preview browser. Clicking the
crosshair button in the chrome row activates a blue-highlight picker
inside the guest webview; clicking an element captures its component
name (via react-grab), source location, html/css preview, and selector,
then attaches it to the chat composer as a chip that serializes into an
`<element_context>` block in the outgoing message.

Architecture:
- Per-`<webview>` preload bundle (`preview-pick-preload.cjs`) renders
  the overlay, hosts the picker event loop, and bubbles the picked
  payload back to main via the per-WebContents `wc.ipc` channel (not
  `sendToHost`, which only fires on the host renderer's <webview>
  element and never reaches main).
- Main coordinates via `PreviewViewManager.pickElement(tabId)`, which
  cancels any in-flight session, force-focuses the guest (so the first
  click on a remote page actually reaches the preload), then awaits the
  payload. User-initiated cancels (Escape, beforeunload) echo `null`
  back to main; main-initiated cancels and supersession tear down
  silently to avoid the new-pick-resolves-with-stale-null race.
- Renderer fetches partition + webPreferences + preload URL in a single
  `getPreviewConfig()` IPC call, snapshots the previously-focused host
  element before triggering a pick, and restores focus when the pick
  resolves so the user's textarea cursor isn't lost.

Security posture for the guest webview:
- `webpreferences="contextIsolation=false,sandbox=true,nodeIntegration=false"`
  centralized in `preview-webview-preferences.ts`. contextIsolation off
  is required so react-grab's `getElementContext` can reach the page's
  React DevTools hook on `globalThis`. sandbox stays on so the page
  cannot reach Node APIs even with shared globals (without it, the
  preload's `require` would land on the page's `globalThis` and any
  third-party site could send arbitrary IPC to main).
- Defense in depth: a `will-attach-webview` handler in main, gated on
  the preview partition, force-pins `sandbox: true`, all
  `nodeIntegration*: false`, and the absolute preload PATH (not URL —
  that field rejects file:// URLs with "preload script must have
  absolute path" and silently disables the picker).

Composer + transcript integration:
- New `elementContexts` slice in `composerDraftStore` (mirrors the
  terminal-context slice: dedup by selector+tag+component+url, persist
  via partializer, restore on send-failure retry).
- `ComposerPendingElementContexts` chip row above the editor.
- `deriveDisplayedUserMessageState` now strips both `<element_context>`
  AND `<terminal_context>` blocks (element first, since it's appended
  last) and exposes element entries to `MessagesTimeline`, which renders
  them as compact chips beneath the message body.
- Pick button is disabled with explanatory tooltip when the page failed
  to load (the React `<PreviewUnreachable>` overlay covers the webview,
  so picks would silently dangle otherwise).

Tests added:
- `preview-webview-preferences.test.ts` locks down the security flags
  (contextIsolation=false, sandbox=true, nodeIntegration=false, no
  whitespace, only true/false literal values).
- `preview-pick-label-position.test.ts` covers the floating-label
  clamp/flip math (no off-screen overflow, flip-below when no room
  above, etc.).
- `picked-element-payload.test.ts` validator coverage.
- `elementContext.test.ts` for the serialization round-trip,
  normalization, dedup, and label formatting.
- `composerDraftStore.test.ts` element-contexts slice (add, dedup,
  remove, set, clear, persistence round-trip).
- `ChatView.logic.test.ts` sendable-content-with-element-only.

Build: new `tsdown` entry inlines react-grab + bippy into the picker
preload bundle (~59KB / 19KB gzipped).
2026-06-13 22:18:37 -07:00

212 lines
6.8 KiB
TypeScript

import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
appendTerminalContextsToPrompt,
buildTerminalContextPreviewTitle,
buildTerminalContextBlock,
countInlineTerminalContextPlaceholders,
deriveDisplayedUserMessageState,
ensureInlineTerminalContextPlaceholders,
extractTrailingTerminalContexts,
filterTerminalContextsWithText,
formatInlineTerminalContextLabel,
formatTerminalContextLabel,
hasTerminalContextText,
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
insertInlineTerminalContextPlaceholder,
isTerminalContextExpired,
materializeInlineTerminalContextPrompt,
removeInlineTerminalContextPlaceholder,
stripInlineTerminalContextPlaceholders,
type TerminalContextDraft,
} from "./terminalContext";
function makeContext(overrides?: Partial<TerminalContextDraft>): TerminalContextDraft {
return {
id: "context-1",
threadId: ThreadId.make("thread-1"),
terminalId: "default",
terminalLabel: "Terminal 1",
lineStart: 12,
lineEnd: 13,
text: "git status\nOn branch main",
createdAt: "2026-03-13T12:00:00.000Z",
...overrides,
};
}
describe("terminalContext", () => {
it("formats terminal labels with line ranges", () => {
expect(formatTerminalContextLabel(makeContext())).toBe("Terminal 1 lines 12-13");
expect(
formatTerminalContextLabel(
makeContext({
lineStart: 9,
lineEnd: 9,
}),
),
).toBe("Terminal 1 line 9");
});
it("builds a numbered terminal context block", () => {
expect(buildTerminalContextBlock([makeContext()])).toBe(
[
"<terminal_context>",
"- Terminal 1 lines 12-13:",
" 12 | git status",
" 13 | On branch main",
"</terminal_context>",
].join("\n"),
);
});
it("appends terminal context blocks after prompt text", () => {
expect(appendTerminalContextsToPrompt("Investigate this", [makeContext()])).toBe(
[
"Investigate this",
"",
"<terminal_context>",
"- Terminal 1 lines 12-13:",
" 12 | git status",
" 13 | On branch main",
"</terminal_context>",
].join("\n"),
);
});
it("replaces inline placeholders with inline terminal labels before appending context blocks", () => {
expect(
appendTerminalContextsToPrompt(
`Investigate ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} carefully`,
[makeContext()],
),
).toBe(
[
"Investigate @terminal-1:12-13 carefully",
"",
"<terminal_context>",
"- Terminal 1 lines 12-13:",
" 12 | git status",
" 13 | On branch main",
"</terminal_context>",
].join("\n"),
);
});
it("extracts terminal context blocks from message text", () => {
const prompt = appendTerminalContextsToPrompt("Investigate this", [makeContext()]);
expect(extractTrailingTerminalContexts(prompt)).toEqual({
promptText: "Investigate this",
contextCount: 1,
previewTitle: "Terminal 1 lines 12-13\n12 | git status\n13 | On branch main",
contexts: [
{
header: "Terminal 1 lines 12-13",
body: "12 | git status\n13 | On branch main",
},
],
});
});
it("derives displayed user message state from terminal context prompts", () => {
const prompt = appendTerminalContextsToPrompt("Investigate this", [makeContext()]);
expect(deriveDisplayedUserMessageState(prompt)).toEqual({
visibleText: "Investigate this",
copyText: prompt,
contextCount: 1,
previewTitle: "Terminal 1 lines 12-13\n12 | git status\n13 | On branch main",
contexts: [
{
header: "Terminal 1 lines 12-13",
body: "12 | git status\n13 | On branch main",
},
],
elementContexts: [],
});
});
it("preserves prompt text when no trailing terminal context block exists", () => {
expect(extractTrailingTerminalContexts("No attached context")).toEqual({
promptText: "No attached context",
contextCount: 0,
previewTitle: null,
contexts: [],
});
});
it("returns null preview title when every context is invalid", () => {
expect(
buildTerminalContextPreviewTitle([
makeContext({
terminalId: " ",
}),
makeContext({
id: "context-2",
text: "\n\n",
}),
]),
).toBeNull();
});
it("tracks inline terminal context placeholders in prompt text", () => {
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
expect(countInlineTerminalContextPlaceholders(`a${placeholder}b${placeholder}`)).toBe(2);
expect(ensureInlineTerminalContextPlaceholders("Investigate this", 2)).toBe(
`${placeholder}${placeholder}Investigate this`,
);
expect(insertInlineTerminalContextPlaceholder("abc", 1)).toEqual({
prompt: `a ${placeholder} bc`,
cursor: 4,
contextIndex: 0,
});
expect(removeInlineTerminalContextPlaceholder(`a${placeholder}b${placeholder}c`, 1)).toEqual({
prompt: `a${placeholder}bc`,
cursor: 3,
});
expect(stripInlineTerminalContextPlaceholders(`a${placeholder}b`)).toBe("ab");
});
it("inserts a placeholder after a file mention when given the expanded prompt cursor", () => {
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
expect(insertInlineTerminalContextPlaceholder("Inspect @package.json ", 22)).toEqual({
prompt: `Inspect @package.json ${placeholder} `,
cursor: 24,
contextIndex: 0,
});
});
it("adds a trailing space and consumes an existing trailing space at the insertion point", () => {
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
expect(insertInlineTerminalContextPlaceholder("yo whats", 3)).toEqual({
prompt: `yo ${placeholder} whats`,
cursor: 5,
contextIndex: 0,
});
});
it("marks contexts without snapshot text as expired and filters them from sendable contexts", () => {
const liveContext = makeContext();
const expiredContext = makeContext({
id: "context-2",
text: "",
});
expect(hasTerminalContextText(liveContext)).toBe(true);
expect(isTerminalContextExpired(liveContext)).toBe(false);
expect(hasTerminalContextText(expiredContext)).toBe(false);
expect(isTerminalContextExpired(expiredContext)).toBe(true);
expect(filterTerminalContextsWithText([expiredContext, liveContext])).toEqual([liveContext]);
});
it("formats and materializes inline terminal labels from placeholder positions", () => {
expect(formatInlineTerminalContextLabel(makeContext())).toBe("@terminal-1:12-13");
expect(
materializeInlineTerminalContextPrompt(
`Investigate ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} carefully`,
[makeContext()],
),
).toBe("Investigate @terminal-1:12-13 carefully");
});
});