fix(app): find sessions when tagging with @ (#57683)

This commit is contained in:
Kit Langton
2026-10-21 08:54:14 -07:00
committed by GitHub
Unverified
parent 320006a0dc
commit 3f4c0e7f38
7 changed files with 200 additions and 21 deletions
@@ -38,6 +38,55 @@ test("mention a session by title, send its stable token, and open its own tab",
await expect(page.locator('[data-titlebar-tab-slot][data-active="true"]')).toContainText("Auth middleware")
})
test("a bare @ lists sessions, and a multi-word title matches while file search is slow", async ({ page }) => {
const target = "ses_0123456789opencodeconsolex"
const prompts: Parameters<NonNullable<MockServerConfig["onPrompt"]>>[0]["body"][] = []
const view = await openSession(page, {
name: "SessionMentionSearch",
findFiles: () => [],
sessions: [
{ id: "ses_mention_search_source", title: "Review the plan" },
{ id: "ses_0123456789homesessionabcde", title: "HOME" },
{ id: target, title: "OPENCODE CONSOLE" },
],
seed: { tabs: ["ses_mention_search_source"] },
onPrompt: (input) => void prompts.push(input.body),
})
const suggestions = page.locator('[data-component="composer-suggestions"]')
const files = await holdRoute(page, (url) => url.pathname === "/api/fs/find")
await view.editor.pressSequentially("Compare with @")
await expect(suggestions.getByRole("button", { name: /HOME/ })).toBeVisible()
await expect(suggestions.getByRole("button", { name: /OPENCODE CONSOLE/ })).toBeVisible()
await view.editor.pressSequentially("open")
await files.arrived
await view.editor.pressSequentially(" con")
await expect(suggestions.getByRole("button", { name: /HOME/ })).toHaveCount(0)
await expect(suggestions.locator("[data-suggestion-id][data-active]")).toContainText("OPENCODE CONSOLE")
await view.editor.press("Enter")
await expect(view.editor.locator('[data-mention="session"]')).toHaveText("@OPENCODE CONSOLE")
files.release()
// Prose after a completed mention neither reopens the popover nor lets it take Enter.
await view.editor.pressSequentially("on code")
await expect(suggestions).toBeHidden()
await view.editor.press("Enter")
await expect.poll(() => prompts.length).toBe(1)
expect(prompts[0]?.text).toBe(`Compare with @session:${target} on code`)
// A space after a full title ends a typed mention, so the rest stays prose.
await view.editor.pressSequentially("@home")
await expect(suggestions.getByRole("button", { name: /HOME/ })).toBeVisible()
await view.editor.pressSequentially(" now")
await expect(suggestions).toBeHidden()
await view.editor.press("Enter")
await expect.poll(() => prompts.length).toBe(2)
expect(prompts[1]?.text).toBe("@home now")
})
test("a catalog refresh cannot replace an existing session's model", async ({ page }) => {
const alpha = { id: "alpha", name: "Alpha", variants: { high: {} } }
const beta = { id: "beta", name: "Beta" }
@@ -66,8 +66,11 @@ export function createComposerEditor(input: {
history?: ComposerHistory
commands: Accessor<ComposerSuggestion[]>
context: Accessor<ComposerSuggestion[]>
searchContextFiles: (query: string) => ComposerSuggestion[] | Promise<ComposerSuggestion[]>
searchSessions?: (query: string) => Promise<ComposerSuggestion[]>
searchContextFiles: (query: string, signal?: AbortSignal) => ComposerSuggestion[] | Promise<ComposerSuggestion[]>
/** Reads reactively, so newly found sessions refresh the list without waiting on file search. */
searchSessions?: (query: string) => ComposerSuggestion[]
/** Whether the session search for this query has yet to settle; reads reactively. */
sessionsPending?: (query: string) => boolean
openAttachment?: (attachment: ComposerAttachment, origin?: HTMLElement) => void
/** An object URL for the image file at this path, which a path attachment references without its bytes. */
readImage?: (path: string) => Promise<string | undefined>
@@ -157,19 +160,58 @@ export function createComposerEditor(input: {
)
}
const [found, setFound] = createStore<{ query: string; files: ComposerSuggestion[] }>({ query: "", files: [] })
let fileQuery: string | undefined
let fileAbort = new AbortController()
onCleanup(() => fileAbort.abort())
// Debounced and abortable: each keystroke or close replaces the pending file search instead of queueing behind it.
const findFiles = (query?: string) => {
if (query === fileQuery) return
fileAbort.abort()
const abort = new AbortController()
fileQuery = query
fileAbort = abort
if (query === undefined) return
if (!query.trim() || /\s/.test(query)) return
const timer = setTimeout(
() =>
void Promise.resolve(input.searchContextFiles(query, abort.signal)).then(
(files) => !abort.signal.aborted && setFound({ query, files }),
() => undefined,
),
150,
)
abort.signal.addEventListener("abort", () => clearTimeout(timer), { once: true })
}
const contextList = useFilteredList<ComposerSuggestion>({
items: async (query) => {
items: (query) => {
if (state.popover.type !== "context") {
findFiles(undefined)
return []
}
findFiles(query)
const sessions = input.searchSessions?.(query) ?? []
// Only session titles contain spaces; fuzzy matches elsewhere would keep the popover over prose.
if (/\s/.test(query)) return sessions
const fixed = input.context().filter((item) => item.kind !== "file")
const recent = input.context().filter((item) => item.kind === "file" && item.recent)
const seen = new Set(recent.map((item) => item.id))
const [sessions, files] = await Promise.all([
input.searchSessions?.(query) ?? [],
query.trim() ? input.searchContextFiles(query) : [],
])
const files = found.query === query ? found.files : []
return [...sessions, ...fixed, ...recent, ...files.filter((item) => !seen.has(item.id))]
return [...fixed, ...sessions, ...recent, ...files.filter((item) => !seen.has(item.id))]
},
key: (item) => item.id,
filterKeys: ["label"],
@@ -190,7 +232,7 @@ export function createComposerEditor(input: {
return "file"
},
sortGroupsBy: (a, b) => {
const order = ["session", "reference", "skill", "agent", "resource", "recent", "file"]
const order = ["reference", "agent", "session", "skill", "resource", "recent", "file"]
return order.indexOf(a.category) - order.indexOf(b.category)
},
@@ -427,6 +469,15 @@ export function createComposerEditor(input: {
dispatch({ type: "popover.results", ids })
})
// A space ends the mention once nothing matches, so `@` can still start ordinary prose.
createEffect(() => {
if (state.popover.type !== "context" || !/\s/.test(state.popover.query)) return
if (input.sessionsPending?.(state.popover.query)) return
if (contextList.grouped.state === "ready" && contextList.flat().length === 0) dispatch({ type: "popover.close" })
})
const restoreFocus = (cursor = draft.state.cursor ?? promptLength(draft.state.prompt)) => {
cancelFocus()
focusCursor = cursor
+36 -8
View File
@@ -2,7 +2,7 @@ import { ImagePreview } from "@opencode/ui/image-preview"
import { useDialog } from "@opencode/ui/context/dialog"
import type { ReferenceInfo } from "@opencode/client/promise"
import type { Links, MountedSession } from "@opencode/gui-extensions/sdk"
import { createComponent, createEffect, createMemo, on, onCleanup } from "solid-js"
import { createComponent, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"
import { Predicate } from "effect"
import type { ComposerSuggestion } from "./types"
import { createComposerEditor, createComposerEditorState, type ComposerEditorModel } from "./editor/interaction"
@@ -23,7 +23,8 @@ import { formatServerError } from "@/runtime/server/errors"
import { Skill } from "@opencode/schema/skill"
import { Session } from "@opencode/schema/session"
import { parseSessionMention } from "@opencode/util/session-mention"
import { createServerSessionEntries } from "@/shell/commands/palette"
import { createKnownServerSessions, createServerSessionEntries } from "@/shell/commands/palette"
import { matchesSessionTitle } from "./session-match"
import type { ComposerAdapter, ComposerControls, ComposerQueue } from "./adapter"
import { isAttachment } from "./prompt-parts"
import { isCommentItem } from "./state"
@@ -202,8 +203,12 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
const skills = createMemo(() => data.location.skill.list({ directory: sdk().directory }) ?? [])
let sessionSearch: string | undefined
const [sessionSearched, setSessionSearched] = createSignal<string>()
const sessions = createServerSessionEntries({
server: server.key,
known: createKnownServerSessions(server.ctx),
projects: server.ctx.projects.list,
load: async (search, signal) => {
const page = await serverSDK.api.session.list({ parentID: null, search, limit: 50 }, { signal })
@@ -353,11 +358,28 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
},
commands,
context,
searchSessions: async (query) => {
if (interaction[0].popover.type !== "context") return []
searchSessions: (query) => {
if (interaction[0].popover.type !== "context") {
// Closing aborts the search, so reopening on the same query must fetch again.
sessionSearch = undefined
return (await sessions(query))
.sort((a, b) => (b.updated ?? 0) - (a.updated ?? 0))
return []
}
// The server narrows by the first word; the title match then needs the whole query.
const search = firstWord(query)
if (search !== sessionSearch) {
sessionSearch = search
void sessions.search(search).then(
() => sessionSearch === search && setSessionSearched(search),
() => sessionSearch === search && setSessionSearched(search),
)
}
return sessions
.items(search)
.filter((entry) => !query || matchesSessionTitle(entry.title, query))
.flatMap((entry): ComposerSuggestion[] => {
if (adapter.kind === "active-session" && entry.sessionID === adapter.session().id) return []
const mention = entry.sessionID && parseSessionMention(entry.sessionID)
@@ -380,9 +402,11 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
},
]
})
.slice(0, query ? 8 : 5)
},
searchContextFiles: async (query) =>
(await files.searchFilesAndDirectories(query)).map((path) => ({
sessionsPending: (query) => sessionSearched() !== firstWord(query),
searchContextFiles: async (query, signal) =>
(await files.searchFilesAndDirectories(query, { signal })).map((path) => ({
id: `file:${path}`,
kind: "file",
label: path,
@@ -613,3 +637,7 @@ function openComment(
if (item.commentOrigin === "review") return queueFocus()
void Promise.resolve(files.load(item.path)).finally(() => queueFocus())
}
function firstWord(query: string) {
return query.toLowerCase().split(" ")[0] ?? ""
}
@@ -0,0 +1,17 @@
import { expect, test } from "bun:test"
import { matchesSessionTitle } from "./session-match"
test.each([
{ title: "OPENCODE CONSOLE", query: "open con", matches: true },
{ title: "OPENCODE CONSOLE", query: "OPENCODE CONSOLE", matches: true },
{ title: "OPENCODE CONSOLE", query: "console", matches: true },
{ title: "OPENCODE CONSOLE", query: "OPENCODE CONSOLE ", matches: false },
{ title: "OPENCODE CONSOLE", query: "OPENCODE CONSOLE on", matches: false },
{ title: "HOME", query: "HOME ", matches: false },
{ title: "HOME", query: "home", matches: true },
{ title: "foobar", query: "foo bar", matches: false },
{ title: "foo bar", query: "foo bar", matches: true },
{ title: "console", query: "sole", matches: false },
])("$query against $title: $matches", (row) => {
expect(matchesSessionTitle(row.title, row.query)).toBe(row.matches)
})
@@ -0,0 +1,10 @@
/**
* Each query word must start consecutive title words, case-insensitively. A trailing space asks for one more
* title word, so `@HOME ` stops matching "HOME" and the popover gives way to prose.
*/
export function matchesSessionTitle(title: string, query: string) {
const words = query.toLowerCase().split(" ")
const titleWords = title.toLowerCase().split(/\s+/).filter(Boolean)
return titleWords.some((_, start) => words.every((word, index) => titleWords[start + index]?.startsWith(word)))
}
@@ -79,6 +79,26 @@ test.each<{
draft: persisted("alpha @sr omega", 9),
popover: { type: "context", query: "sr" },
},
{
name: "keeps an open mention searching across single spaces",
from: { popover: { type: "context", query: "open" } },
event: { type: "input.changed", value: "see @open con", persist: false },
draft: persisted("see @open con"),
popover: { type: "context", query: "open con" },
},
{
name: "does not reopen a mention across a space",
event: { type: "input.changed", value: "see @open con", persist: false },
draft: persisted("see @open con"),
popover: { type: "closed" },
},
{
name: "ends an open mention at a double space",
from: { popover: { type: "context", query: "open " } },
event: { type: "input.changed", value: "see @open ", persist: false },
draft: persisted("see @open "),
popover: { type: "closed" },
},
{
name: "enters shell mode from an initial exclamation mark",
event: { type: "input.changed", value: "!", persist: false },
@@ -126,7 +126,10 @@ function inputChanged(
])
}
const context = value.slice(0, cursor ?? value.length).match(/(?:^|\s)@([^\s@]*)$/)
// An open mention keeps single spaces so multi-word session titles stay searchable.
const context = value
.slice(0, cursor ?? value.length)
.match(state.popover.type === "context" ? /(?:^|\s)@((?:[^\s@]+(?: [^\s@]+)* ?)?)$/ : /(?:^|\s)@([^\s@]*)$/)
if (context) {
const query = context[1] ?? ""
@@ -249,9 +252,10 @@ function suggestionSelected(
commands.push({
type: "mention.add",
item,
...(item.kind === "skill" && item.label.startsWith("/")
? { range: { start: 0, end: state.popover.type === "command-menu" ? 0 : current.length } }
: {}),
range:
item.kind === "skill" && item.label.startsWith("/")
? { start: 0, end: state.popover.type === "command-menu" ? 0 : current.length }
: undefined,
})
}