Skip to content

Commit f738b32

Browse files
authored
feat(app): jump to an earlier prompt by searching session messages (#63585)
1 parent a73657f commit f738b32

12 files changed

Lines changed: 921 additions & 6 deletions

File tree

‎packages/app/e2e/regression/timeline-history.spec.ts‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
assistantMessage,
88
historyMessages,
99
messageUpdated,
10+
partDelta,
1011
partUpdated,
1112
session,
1213
sessionID,
@@ -23,6 +24,108 @@ import { openSession } from "../utils/workspace"
2324
test.use({ serviceWorkers: "block" })
2425

2526
test.describe("timeline history", () => {
27+
test("jump to message searches offscreen history without moving the reader until selection", async ({ page }) => {
28+
const target = userMessage([textPart("prt_dispatch_note", "Use the loading dock for delivery")], {
29+
id: "msg_00000_dispatch",
30+
created: 1680000000000,
31+
})
32+
33+
const messages = [
34+
target,
35+
...historyMessages(45),
36+
userMessage(),
37+
assistantMessage([textPart("prt_active", "Checking the route")], { completed: false }),
38+
]
39+
40+
const timeline = await setupTimeline(page, {
41+
sessionMessages: messages,
42+
pageMessages: (_, limit, before) => {
43+
const end = before ? messages.findIndex((message) => message.id === before) : messages.length
44+
const start = Math.max(0, end - Math.min(16, limit))
45+
46+
return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
47+
},
48+
})
49+
50+
const scroller = timelineScroller(page)
51+
52+
const old = scroller.getByText(target.text, { exact: true })
53+
54+
await expect(scroller.getByText("Checking the route", { exact: true })).toBeInViewport()
55+
await expect(old).toHaveCount(0)
56+
const top = await scroller.evaluate((element) => element.scrollTop)
57+
58+
const mod = await page.evaluate(() => (/Mac/.test(navigator.platform) ? "Meta" : "Control"))
59+
60+
const search = page.getByRole("combobox", { name: "Jump to message" })
61+
62+
await page.keyboard.press(`${mod}+Alt+g`)
63+
await expect(search).toBeFocused()
64+
await search.fill("loading dock")
65+
await expect(page.getByRole("option", { name: /Use the loading dock/ })).toBeVisible()
66+
await search.press("Escape")
67+
await expect(search).toBeHidden()
68+
expect(await scroller.evaluate((element) => element.scrollTop)).toBe(top)
69+
await expect(old).toHaveCount(0)
70+
71+
await page.keyboard.press(`${mod}+Shift+p`)
72+
await page.getByRole("combobox").fill("sent prompts")
73+
await page.getByRole("option", { name: /Jump to message/ }).click()
74+
await expect(search).toBeFocused()
75+
await search.fill("loading dock")
76+
await expect(page.getByRole("option", { name: /Use the loading dock/ })).toBeVisible()
77+
await search.press("Enter")
78+
await expect(old).toBeInViewport()
79+
await timeline.send(partDelta("prt_active", "\n\nThe route is ready."))
80+
await expect(old).toBeInViewport()
81+
await expect(page).toHaveURL(new RegExp(`#message-${target.id}$`))
82+
await page.getByRole("button", { name: "Jump to latest" }).click()
83+
await expect(scroller.getByText("The route is ready.", { exact: true })).toBeInViewport()
84+
})
85+
86+
test("jump to message pages back only as far as the prompt", async ({ page }) => {
87+
const target = userMessage([textPart("prt_dispatch_note", "Use the loading dock for delivery")], {
88+
id: "msg_00100_dispatch",
89+
created: 1690000000000,
90+
})
91+
92+
const history = historyMessages(80)
93+
94+
const messages = [
95+
...history.slice(0, 100),
96+
target,
97+
...history.slice(100),
98+
userMessage(),
99+
assistantMessage([textPart("prt_active", "Checking the route")], { completed: false }),
100+
]
101+
102+
let oldest = messages.length
103+
104+
await setupTimeline(page, {
105+
sessionMessages: messages,
106+
pageMessages: (_, limit, before) => {
107+
const end = before ? messages.findIndex((message) => message.id === before) : messages.length
108+
const start = Math.max(0, end - Math.min(16, limit))
109+
110+
// The picker lists older prompts in pages of 200 without touching the timeline; the timeline pages by 20.
111+
if (limit < 200) oldest = Math.min(oldest, start)
112+
113+
return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
114+
},
115+
})
116+
117+
const mod = await page.evaluate(() => (/Mac/.test(navigator.platform) ? "Meta" : "Control"))
118+
119+
const search = page.getByRole("combobox", { name: "Jump to message" })
120+
121+
await page.keyboard.press(`${mod}+Alt+g`)
122+
await search.fill("loading dock")
123+
await expect(page.getByRole("option", { name: /Use the loading dock/ })).toBeVisible()
124+
await search.press("Enter")
125+
await expect(timelineScroller(page).getByText(target.text, { exact: true })).toBeInViewport()
126+
expect(oldest).toBeGreaterThan(0)
127+
})
128+
26129
test("restoring a paged transcript waits for another upward scroll before loading history", async ({ page }) => {
27130
const id = "ses_history_restore"
28131
const other = "ses_history_other"

‎packages/app/src/runtime/i18n/en.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,15 @@ export const dict = {
406406
"mcp.timedOut": "{{name}} took too long to respond",
407407

408408
"dialog.fork.empty": "No messages to fork from",
409+
"dialog.jump.title": "Jump to message",
410+
"dialog.jump.description": "Choose a message to jump to",
411+
"command.session.jumpToMessage.description": "Search sent prompts in this session",
412+
"dialog.jump.loading": "Loading older prompts…",
413+
"dialog.jump.opening": "Opening message…",
414+
"dialog.jump.failed": "Couldn’t load the full history.",
415+
"dialog.jump.openFailed": "Couldn’t open that message. Try again.",
416+
"dialog.jump.empty": "No sent prompts yet",
417+
"dialog.jump.noMatches": "No matching prompts",
409418

410419
"dialog.directory.action.selectFile": "Select file",
411420
"dialog.directory.action.selectFolder": "Select folder",
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
import type { SessionMessageUser } from "@opencode/client/promise"
2+
import { useDialog } from "@opencode/ui/context/dialog"
3+
import { createEffect, createMemo, createSignal, onCleanup } from "solid-js"
4+
import { readPromptPresentation } from "@/composer/comment-note"
5+
import { useLanguage } from "@/runtime/i18n/language"
6+
import { useServerSDK } from "@/runtime/server/client"
7+
import { useData } from "@/runtime/server/current"
8+
import type { SessionCommandContext } from "./use-session-commands"
9+
import { parseVoiceDelegation } from "../timeline/voice-delegation"
10+
import { JumpToMessage, type JumpPrompt } from "./jump-to-message"
11+
import {
12+
selectJumpHistory,
13+
selectJumpOpening,
14+
selectJumpStatus,
15+
startJumpToMessage,
16+
transitionJumpToMessage,
17+
type JumpToMessageEffect,
18+
type JumpToMessageEvent,
19+
} from "./jump-to-message-machine"
20+
21+
function prompt(message: SessionMessageUser, attachment: string): JumpPrompt {
22+
const presentation = readPromptPresentation(message.metadata)
23+
24+
const text = presentation?.displayText ?? message.text
25+
26+
const voice = parseVoiceDelegation(text)
27+
28+
const labels = [
29+
voice?.framing ?? voice?.instruction ?? text,
30+
...(presentation?.attachments ?? []).map((file) => file.name),
31+
...(message.files ?? []).filter((file) => !file.mention).map((file) => file.name || attachment),
32+
...(message.agents ?? []).filter((agent) => !agent.mention).map((agent) => `@${agent.name}`),
33+
...(message.skills ?? []).filter((skill) => !skill.mention).map((skill) => skill.name),
34+
...(presentation?.comments ?? []).map((comment) => {
35+
if (comment.comment) return comment.comment
36+
37+
if (comment.type === "quote") return comment.text
38+
39+
if (comment.type === "note") return comment.subject
40+
41+
return comment.path
42+
}),
43+
]
44+
45+
return {
46+
id: message.id,
47+
text: labels.filter(Boolean).join("\n"),
48+
created: message.time.created,
49+
}
50+
}
51+
52+
export function DialogJumpToMessage(props: {
53+
session: SessionCommandContext["session"]
54+
onJump: (id: string) => void
55+
}) {
56+
const dialog = useDialog()
57+
const language = useLanguage()
58+
const data = useData()
59+
const sdk = useServerSDK()
60+
const key = props.session.identity.sessionKey()
61+
const id = props.session.identity.params.id
62+
63+
if (!id) return void dialog.close()
64+
let controller: AbortController | undefined
65+
const start = startJumpToMessage()
66+
67+
const [state, setState] = createSignal(start.state)
68+
69+
const dispatch = (event: JumpToMessageEvent) => {
70+
const next = transitionJumpToMessage(state(), event)
71+
72+
if (next.state !== state()) setState(next.state)
73+
next.effects.forEach(run)
74+
}
75+
76+
const run = (effect: JumpToMessageEffect) => {
77+
if (effect.type === "cancel") return controller?.abort()
78+
79+
if (effect.type === "jump") {
80+
dialog.close()
81+
82+
return props.onJump(effect.id)
83+
}
84+
85+
controller?.abort()
86+
const current = new AbortController()
87+
88+
controller = current
89+
90+
if (effect.type === "history.load")
91+
return void loadHistory(current.signal).then(
92+
(history) =>
93+
dispatch({
94+
type: "history.loaded",
95+
attempt: effect.attempt,
96+
history,
97+
}),
98+
() => dispatch({ type: "history.failed", attempt: effect.attempt }),
99+
)
100+
101+
void reveal(effect.target, AbortSignal.any([current.signal, AbortSignal.timeout(60_000)])).then(
102+
() => dispatch({ type: "opened", attempt: effect.attempt }),
103+
() => dispatch({ type: "open.failed", attempt: effect.attempt }),
104+
)
105+
}
106+
107+
// Read older prompts into the picker only. Prepending pages to the timeline while browsing would move the reader.
108+
const loadHistory = async (signal: AbortSignal) => {
109+
const rows: JumpPrompt[] = []
110+
111+
// Join the timeline's initial sync before interpreting a missing cursor as the end of history.
112+
await data.session.message.sync(id)
113+
signal.throwIfAborted()
114+
115+
if (!data.session.message.more(id)) return rows
116+
let cursor: string | undefined
117+
118+
do {
119+
const page = await sdk.api.message.list(
120+
{ sessionID: id, type: "user", limit: 200, cursor },
121+
{ signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]) },
122+
)
123+
124+
signal.throwIfAborted()
125+
126+
for (const message of page.data) {
127+
if (message.type === "user") rows.push(prompt(message, language.t("common.attachment")))
128+
}
129+
130+
cursor = page.cursor.next ?? undefined
131+
} while (cursor)
132+
133+
return rows
134+
}
135+
136+
// Page back only as far as the prompt, so the rest of a long session stays unloaded.
137+
const reveal = async (messageID: string, signal: AbortSignal) => {
138+
while (!data.session.message.get(id, messageID)) {
139+
if (!data.session.message.more(id)) throw new Error("Message unavailable")
140+
await data.session.message.loadMore(id, { signal })
141+
signal.throwIfAborted()
142+
}
143+
144+
if (
145+
!props.session.history.visibleUserMessages().some((message) => message.id === messageID) ||
146+
data.session.input.has(id, messageID)
147+
)
148+
throw new Error("Message unavailable")
149+
}
150+
151+
start.effects.forEach(run)
152+
onCleanup(() => dispatch({ type: "disposed" }))
153+
createEffect(() => {
154+
if (key !== props.session.identity.sessionKey() || dialog.closing) dispatch({ type: "disposed" })
155+
156+
if (key !== props.session.identity.sessionKey()) dialog.close()
157+
})
158+
159+
const prompts = createMemo(() => {
160+
const all = new Map(selectJumpHistory(state()).map((row) => [row.id, row]))
161+
162+
const reverted = data.session.get(id)?.revert?.messageID
163+
164+
for (const message of props.session.history.visibleUserMessages()) {
165+
all.set(message.id, prompt(message, language.t("common.attachment")))
166+
}
167+
168+
const pending = new Set(data.session.input.list(id))
169+
170+
return [...all.values()].filter(
171+
(row) => row.text.trim() && !pending.has(row.id) && (!reverted || row.id < reverted),
172+
)
173+
})
174+
175+
const status = () => {
176+
const note = selectJumpStatus(state())
177+
178+
return note && language.t(`dialog.jump.${note}`)
179+
}
180+
181+
return (
182+
<JumpToMessage
183+
prompts={prompts()}
184+
opening={selectJumpOpening(state())}
185+
status={status()}
186+
onRetry={state().status === "failed" ? () => dispatch({ type: "retry" }) : undefined}
187+
onClose={() => dialog.close()}
188+
onJump={(row) =>
189+
dispatch({
190+
type: "selected",
191+
id: row.id,
192+
loaded: !!data.session.message.get(id, row.id),
193+
})
194+
}
195+
/>
196+
)
197+
}

0 commit comments

Comments
 (0)