Skip to content

Commit 012b8eb

Browse files
feat(tui): make pasted-text placeholders expandable and collapsible
A pasted [Pasted ~N lines] placeholder in the prompt can now be expanded to its full content and collapsed back -- click it, or run "Expand/collapse pasted text" (prompt.paste.toggle) from the palette or a keybind. Ported from upstream anomalyco#8501 (325 reactions -- the highest of any issue found across a full survey of this repo's open issues). A trivial 1-file fix already merged upstream as anomalyco#39920 isn't even on this fork's history and is a one-way, no-collapse expand anyway, not the real ask. Richer attempts were all closed by the automated PR-cleanup bot and never reviewed: - PR anomalyco#41813 "paste expand toggle" is the primary source: a pasted- text part remembers its original placeholder so it can collapse again, the chip is swapped by deleting its extmark, replacing the selected text, and recreating the extmark over the new text. - PR anomalyco#33700 fixed a real, separate bug reused as-is: expandPastedTextPlaceholders substituted text back in via String.replace(str, str2), which treats $&/$$/etc. in the pasted text as special replacement patterns and silently corrupts it -- fixed by passing a replacer function instead of a literal string. - PR anomalyco#37052 contributed only the idea of a palette command to expand chips (its own version was one-way, expand-all); this fork's version is a proper per-chip toggle. New: older saved prompts with no stored placeholder can still be expanded (anomalyco#41813's version would lock them collapsed-only). Two pure functions (togglePastedText, replaceVirtualExtmarkText) were extracted into packages/tui/src/prompt/part.ts so anomalyco#41813's logic is unit- testable outside the full Prompt component. Known gaps: the full Prompt component's mouse-click path has no automated test (no existing fixture mounts it with SDK/sync/route providers -- checked manually against a bare textarea instead); clicking a chip's very last character can miss the same way it does in anomalyco#41813; an expanded chip is viewable but not editable in place. New tests in packages/tui/test/prompt/part.test.ts and a new packages/tui/test/prompt/paste-toggle.test.tsx (using this repo's existing testRender/mockMouse helpers). Verified against this fork's current dev (not just the agent's own stale worktree base): bun typecheck clean; full packages/tui suite 215 pass. Co-Authored-By: Claude Sonnet 5 <[email protected]>
1 parent 98df7b5 commit 012b8eb

8 files changed

Lines changed: 258 additions & 12 deletions

File tree

‎FORK_CHANGES.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,17 @@ Each entry names the upstream gap it addresses, whether it originated as our own
66

77
## Implemented
88

9+
### Expandable pasted-text placeholders
10+
11+
A pasted `[Pasted ~N lines]` placeholder in the TUI prompt can now be expanded to its full content and collapsed back — click it, or run "Expand/collapse pasted text" (`prompt.paste.toggle`) from the command palette or a keybind.
12+
13+
- **Upstream gap:** [anomalyco/opencode#8501](https://github.com/anomalyco/opencode/issues/8501) — **325 reactions**, the single highest-reaction issue found across a full survey of this repo's open issues. A trivial 1-file fix already merged upstream as PR #39920, but the issue stayed open because that fix is a one-way, no-collapse click-to-expand, not the real ask — and it isn't even present on this fork's history (its merge commit exists but isn't an ancestor of `dev`). Richer attempts, all closed by the automated PR-cleanup bot (>1 month old, <2 reactions) and never reviewed: [PR #41813](https://github.com/anomalyco/opencode/pull/41813) "paste expand toggle" (primary source), [PR #33700](https://github.com/anomalyco/opencode/pull/33700) "expand pasted text placeholders literally", and the tokens/sec-bundled [PR #37052](https://github.com/anomalyco/opencode/pull/37052) (only its expand-related idea used; the rest is unrelated and was independently ported for the tokens/sec feature above).
14+
- **Origin:** implemented by an Opus 5 agent. #41813's logic is reused almost as-is: a pasted-text part remembers its original placeholder so it can collapse again after expanding, the chip is swapped by deleting its extmark, replacing the selected text, and recreating the extmark over the new text, and a guard stops the prompt's own content-change sync from dropping the part mid-swap. #33700 fixed a real, separate bug reused as-is: `expandPastedTextPlaceholders` used to substitute pasted text back in via `String.replace(str, str2)`, which treats `$&`/`$$`/etc. in the pasted text as special replacement patterns and silently corrupts it — fixed by passing a replacer function instead of a literal string. #37052 contributed only the idea of a palette command to expand chips (its own version was one-way, collapse-all); this fork's version is a proper toggle on the chip under the cursor. Two pure, newly-extracted, unit-tested functions (`togglePastedText`, `replaceVirtualExtmarkText` in `packages/tui/src/prompt/part.ts`) hold #41813's logic so it's testable outside the full `Prompt` component. New: older saved prompts with no stored placeholder (from before this field existed) can still be expanded, where #41813's own version would lock them collapsed-only; `try`/`finally` around the swap was dropped per this repo's avoid-`try`/`catch` convention.
15+
- **Where:** `packages/tui/src/component/prompt/index.tsx` (click handling + the new `prompt.paste.toggle` command), `packages/tui/src/prompt/part.ts` (the two extracted pure functions), `packages/tui/src/prompt/history.tsx` (a `placeholder` field on the saved pasted-text-part type), `packages/tui/src/config/keybind.ts` (a `prompt_paste_toggle` keybind slot, unbound by default like other prompt commands).
16+
- **Known gaps:** the full `Prompt` component's actual mouse-click path (as opposed to the pure toggle/swap functions) has no test — mounting it needs SDK/sync/route providers with no existing fixture for that; the click behavior was checked manually against a bare `<textarea>` firing the same mouse events instead. Clicking a chip's very last character can miss (the cursor then sits just past the chip's end, which the editor library's extmark lookup doesn't count as "inside" it) — the same limitation exists in #41813. An expanded chip remains a single cursor unit with the paste-highlight style; its text is viewable but not editable in place, matching #41813.
17+
- **Verified:** `bun typecheck` clean in `packages/tui`. New tests in `packages/tui/test/prompt/part.test.ts` (pure toggle/collapse cases) and a new `packages/tui/test/prompt/paste-toggle.test.tsx` (using a real `<textarea>` via this repo's existing `testRender`/`mockMouse` test helpers, matching `test/cli/tui/dialog-prompt.test.tsx`'s established pattern) covering expand/collapse in place, later chips shifting correctly after a swap, and the cursor landing inside the chip after a click. Full `packages/tui` suite (re-verified against this fork's current `dev`, not just the agent's own stale worktree base, and after the tokens/sec feature above): 215 pass.
18+
- **Where:** [`dev` branch history](https://github.com/chipp-ai/opencode/commits/dev).
19+
920
### Per-call subagent model selection (Task tool)
1021

1122
The primary agent can now override which model a specific `task` dispatch uses (`model: "provider/model-id"`, plus an optional `variant`), instead of every dispatch always using the subagent's statically-configured model.

‎packages/tui/src/component/prompt/index.tsx‎

Lines changed: 85 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ import {
33
RGBA,
44
TextareaRenderable,
55
MouseEvent,
6+
MouseButton,
67
PasteEvent,
78
decodePasteBytes,
9+
type Extmark,
810
type KeyEvent,
911
type Renderable,
1012
} from "@opentui/core"
@@ -32,7 +34,12 @@ import { promptOffsetWidth } from "../../prompt/display"
3234
import { createStore, produce, unwrap } from "solid-js/store"
3335
import { usePromptHistory, type PromptInfo } from "../../prompt/history"
3436
import { computePromptTraits } from "../../prompt/traits"
35-
import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../prompt/part"
37+
import {
38+
expandPastedTextPlaceholders,
39+
expandTrackedPastedText,
40+
replaceVirtualExtmarkText,
41+
togglePastedText,
42+
} from "../../prompt/part"
3643
import { usePromptStash } from "../../prompt/stash"
3744
import { DialogStash } from "../dialog-stash"
3845
import { type AutocompleteRef, Autocomplete } from "./autocomplete"
@@ -234,6 +241,8 @@ export function Prompt(props: PromptProps) {
234241
const agentStyleId = syntax().getStyleId("extmark.agent")!
235242
const pasteStyleId = syntax().getStyleId("extmark.paste")!
236243
let promptPartTypeId = 0
244+
let suppressSync = false
245+
let mouseDown: { x: number; y: number } | undefined
237246
const event = useEvent()
238247

239248
event.on("tui.prompt.append", (evt, { workspace }) => {
@@ -392,6 +401,23 @@ export function Prompt(props: PromptProps) {
392401
}
393402
},
394403
},
404+
{
405+
title: "Expand/collapse pasted text",
406+
name: "prompt.paste.toggle",
407+
category: "Prompt",
408+
enabled: store.prompt.parts.some((part) => part.type === "text" && part.source?.text),
409+
run: () => {
410+
const marks = input.extmarks
411+
.getAllForTypeId(promptPartTypeId)
412+
.filter((mark) => pastedPartIndex(mark) !== undefined)
413+
// Prefer the chip the cursor is on or next to; otherwise the last one in the prompt.
414+
const mark =
415+
marks.find((item) => item.start <= input.cursorOffset && input.cursorOffset <= item.end) ??
416+
marks.toSorted((a, b) => b.start - a.start)[0]
417+
if (mark) togglePastedPart(mark)
418+
dialog.clear()
419+
},
420+
},
395421
{
396422
title: "Interrupt session",
397423
name: "session.interrupt",
@@ -432,12 +458,7 @@ export function Prompt(props: PromptProps) {
432458
dialog.clear()
433459

434460
// replace summarized text parts with the actual text
435-
const text = store.prompt.parts
436-
.filter((p) => p.type === "text")
437-
.reduce((acc, p) => {
438-
if (!p.source) return acc
439-
return acc.replace(p.source.text.value, p.text)
440-
}, store.prompt.input)
461+
const text = expandPastedTextPlaceholders(store.prompt.input, store.prompt.parts)
441462

442463
const nonTextParts = store.prompt.parts.filter((p) => p.type !== "text")
443464

@@ -609,6 +630,7 @@ export function Prompt(props: PromptProps) {
609630
"prompt.stash",
610631
"prompt.stash.pop",
611632
"prompt.stash.list",
633+
"prompt.paste.toggle",
612634
"prompt.skills",
613635
"session.interrupt",
614636
"workspace.set",
@@ -770,6 +792,45 @@ export function Prompt(props: PromptProps) {
770792
)
771793
}
772794

795+
function pastedPartIndex(mark: Extmark) {
796+
const partIndex = store.extmarkToPartIndex.get(mark.id)
797+
if (partIndex === undefined) return
798+
const part = store.prompt.parts[partIndex]
799+
if (part?.type !== "text" || !part.source?.text) return
800+
return partIndex
801+
}
802+
803+
function togglePastedPart(mark: Extmark) {
804+
const partIndex = pastedPartIndex(mark)
805+
const part = partIndex === undefined ? undefined : store.prompt.parts[partIndex]
806+
if (partIndex === undefined || part?.type !== "text" || !part.source) return
807+
const next = togglePastedText({ text: part.text, source: part.source })
808+
if (!next) return
809+
810+
// insertText fires onContentChange synchronously while the part's extmark is deleted;
811+
// syncing then would drop the part.
812+
suppressSync = true
813+
const created = replaceVirtualExtmarkText(input, mark, next.value)
814+
suppressSync = false
815+
816+
setStore(
817+
produce((draft) => {
818+
draft.extmarkToPartIndex.delete(mark.id)
819+
draft.extmarkToPartIndex.set(created.id, partIndex)
820+
const draftPart = draft.prompt.parts[partIndex]
821+
if (draftPart?.type !== "text" || !draftPart.source) return
822+
draftPart.source.text = {
823+
start: created.start,
824+
end: created.end,
825+
value: next.value,
826+
placeholder: next.placeholder,
827+
}
828+
}),
829+
)
830+
// The width change shifts the ranges of later chips.
831+
syncExtmarksWithPromptParts()
832+
}
833+
773834
const stashCommands = createMemo(() =>
774835
[
775836
{
@@ -1209,6 +1270,7 @@ export function Prompt(props: PromptProps) {
12091270
start: extmarkStart,
12101271
end: extmarkEnd,
12111272
value: virtualText,
1273+
placeholder: virtualText,
12121274
},
12131275
},
12141276
})
@@ -1415,7 +1477,7 @@ export function Prompt(props: PromptProps) {
14151477
const value = input.plainText
14161478
setStore("prompt", "input", value)
14171479
auto()?.onInput(value)
1418-
syncExtmarksWithPromptParts()
1480+
if (!suppressSync) syncExtmarksWithPromptParts()
14191481
setCursorVersion((value) => value + 1)
14201482
}}
14211483
onCursorChange={() => setCursorVersion((value) => value + 1)}
@@ -1472,7 +1534,21 @@ export function Prompt(props: PromptProps) {
14721534
if (tuiConfig.cursor) input.cursorStyle = tuiConfig.cursor
14731535
}, 0)
14741536
}}
1475-
onMouseDown={(r: MouseEvent) => r.target?.focus()}
1537+
onMouseDown={(r: MouseEvent) => {
1538+
r.target?.focus()
1539+
mouseDown = { x: r.x, y: r.y }
1540+
}}
1541+
onMouseUp={(r: MouseEvent) => {
1542+
const start = mouseDown
1543+
mouseDown = undefined
1544+
if (props.disabled || r.button !== MouseButton.LEFT || !start) return
1545+
// A drag selects text; only a click toggles.
1546+
if (Math.abs(r.x - start.x) >= 2 || Math.abs(r.y - start.y) >= 2) return
1547+
const mark = input.extmarks
1548+
.getAtOffset(input.cursorOffset)
1549+
.find((item) => item.typeId === promptPartTypeId && pastedPartIndex(item) !== undefined)
1550+
if (mark) togglePastedPart(mark)
1551+
}}
14761552
focusedBackgroundColor={theme.backgroundElement}
14771553
cursorColor={props.disabled ? theme.backgroundElement : theme.text}
14781554
cursorStyle={tuiConfig.cursor}

‎packages/tui/src/config/keybind.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ export const Definitions = {
156156
prompt_stash: keybind("none", "Stash prompt"),
157157
prompt_stash_pop: keybind("none", "Pop stashed prompt"),
158158
prompt_stash_list: keybind("none", "List stashed prompts"),
159+
prompt_paste_toggle: keybind("none", "Expand or collapse pasted text"),
159160
workspace_set: keybind("none", "Set workspace"),
160161

161162
input_clear: keybind("ctrl+c", "Clear input field"),
@@ -360,6 +361,7 @@ export const CommandMap = {
360361
prompt_stash: "prompt.stash",
361362
prompt_stash_pop: "prompt.stash.pop",
362363
prompt_stash_list: "prompt.stash.list",
364+
prompt_paste_toggle: "prompt.paste.toggle",
363365
workspace_set: "workspace.set",
364366
input_clear: "prompt.clear",
365367
input_paste: "prompt.paste",

‎packages/tui/src/prompt/history.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export type PromptInfo = {
1818
start: number
1919
end: number
2020
value: string
21+
placeholder?: string
2122
}
2223
}
2324
})

‎packages/tui/src/prompt/part.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { displaySlice } from "./display"
1+
import type { Extmark, TextareaRenderable } from "@opentui/core"
2+
import { displaySlice, promptOffsetWidth } from "./display"
23

34
export function stripPromptPartIDs<Part extends { id: string; messageID: string; sessionID: string }>(part: Part) {
45
const { id: _id, messageID: _messageID, sessionID: _sessionID, ...rest } = part
@@ -8,7 +9,7 @@ export function stripPromptPartIDs<Part extends { id: string; messageID: string;
89
export function expandPastedTextPlaceholders(text: string, parts: readonly unknown[]) {
910
return parts.reduce<string>((result, part) => {
1011
if (!isPastedTextPart(part)) return result
11-
return result.replace(part.source.text.value, part.text)
12+
return result.replace(part.source.text.value, () => part.text)
1213
}, text)
1314
}
1415

@@ -27,3 +28,27 @@ export function expandTrackedPastedText(text: string, ranges: { start: number; e
2728
.sort((a, b) => b.start - a.start)
2829
.reduce((result, part) => displaySlice(result, 0, part.start) + part.text + displaySlice(result, part.end), text)
2930
}
31+
32+
// A pasted-text part is expanded when its visible value is the full pasted text. The collapsed
33+
// placeholder is remembered so it can be restored; entries saved before `placeholder` existed
34+
// are always collapsed at that point, so their current value is the placeholder.
35+
export function togglePastedText(part: { text: string; source: { text: { value: string; placeholder?: string } } }) {
36+
const expanded = part.source.text.value === part.text
37+
const placeholder = part.source.text.placeholder ?? (expanded ? undefined : part.source.text.value)
38+
if (placeholder === undefined) return
39+
return { value: expanded ? placeholder : part.text, placeholder }
40+
}
41+
42+
// Replaces the text covered by a virtual extmark and recreates the extmark over the new text,
43+
// keeping its style and type so it still behaves as a single cursor unit.
44+
export function replaceVirtualExtmarkText(input: TextareaRenderable, mark: Extmark, text: string) {
45+
input.extmarks.delete(mark.id)
46+
input.setSelection(mark.start, mark.end)
47+
input.insertText(text)
48+
const end = mark.start + promptOffsetWidth(text)
49+
return {
50+
start: mark.start,
51+
end,
52+
id: input.extmarks.create({ start: mark.start, end, virtual: true, styleId: mark.styleId, typeId: mark.typeId }),
53+
}
54+
}

‎packages/tui/test/prompt/part.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
import { describe, expect, test } from "bun:test"
2-
import { expandTrackedPastedText, stripPromptPartIDs } from "../../src/prompt/part"
2+
import {
3+
expandPastedTextPlaceholders,
4+
expandTrackedPastedText,
5+
stripPromptPartIDs,
6+
togglePastedText,
7+
} from "../../src/prompt/part"
8+
9+
function pastedTextPart(marker: string, text: string) {
10+
return { type: "text" as const, text, source: { text: { value: marker } } }
11+
}
312

413
describe("prompt part", () => {
514
test("strips persisted IDs from reused parts", () => {
@@ -50,4 +59,50 @@ describe("prompt part", () => {
5059
]),
5160
).toBe(`keep ${marker} then alpha\nbeta\ngamma tail`)
5261
})
62+
63+
test("expands placeholders with dollar sequences literally", () => {
64+
const marker = "[Pasted ~1 lines]"
65+
for (const pasted of ["const cost = ${price}$$", "echo $&foo", "a $` b", "x $' y", "price $1 each"]) {
66+
expect(expandPastedTextPlaceholders(`see ${marker} here`, [pastedTextPart(marker, pasted)])).toBe(
67+
`see ${pasted} here`,
68+
)
69+
}
70+
})
71+
72+
test("expands repeated same-line-count placeholders in order", () => {
73+
const marker = "[Pasted ~2 lines]"
74+
expect(
75+
expandPastedTextPlaceholders(`${marker} and ${marker}`, [
76+
pastedTextPart(marker, "first"),
77+
pastedTextPart(marker, "second"),
78+
]),
79+
).toBe("first and second")
80+
})
81+
82+
test("leaves non pasted-text parts untouched", () => {
83+
const marker = "[Pasted ~1 lines]"
84+
expect(
85+
expandPastedTextPlaceholders(`see ${marker} here`, [
86+
{ type: "file", url: "data:," },
87+
pastedTextPart(marker, "$$$"),
88+
]),
89+
).toBe("see $$$ here")
90+
})
91+
92+
test("toggles a pasted part between placeholder and full text", () => {
93+
const marker = "[Pasted ~3 lines]"
94+
const text = "alpha\nbeta\ngamma"
95+
const expanded = togglePastedText({ text, source: { text: { value: marker, placeholder: marker } } })
96+
expect(expanded).toEqual({ value: text, placeholder: marker })
97+
expect(togglePastedText({ text, source: { text: expanded! } })).toEqual({ value: marker, placeholder: marker })
98+
})
99+
100+
test("recovers the placeholder for parts saved before it was tracked", () => {
101+
const marker = "[Pasted ~3 lines]"
102+
expect(togglePastedText({ text: "a\nb\nc", source: { text: { value: marker } } })).toEqual({
103+
value: "a\nb\nc",
104+
placeholder: marker,
105+
})
106+
expect(togglePastedText({ text: "a\nb\nc", source: { text: { value: "a\nb\nc" } } })).toBeUndefined()
107+
})
53108
})

0 commit comments

Comments
 (0)