mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 13:05:14 +03:00
fix(app): stop loading every session for search (#62170)
This commit is contained in:
@@ -132,6 +132,54 @@ test("titlebar search lists recent sessions and opens the typed match", async ({
|
||||
await expect(page.getByRole("heading", { name: paletteSession.title, exact: true })).toBeVisible()
|
||||
})
|
||||
|
||||
test("titlebar search asks for one bounded result set after a pause in typing", async ({ page }) => {
|
||||
await openPaletteWorkspace(page, true)
|
||||
const searches: URL[] = []
|
||||
page.on("request", (request) => {
|
||||
const url = new URL(request.url())
|
||||
|
||||
if (request.method() !== "GET" || url.pathname !== "/api/session") return
|
||||
|
||||
if (!url.searchParams.get("search")) return
|
||||
|
||||
searches.push(url)
|
||||
})
|
||||
await page.getByRole("banner").getByRole("button", { name: "Search sessions", exact: true }).click()
|
||||
const dialog = page.getByRole("dialog")
|
||||
const input = dialog.getByRole("combobox")
|
||||
await expect(dialog.getByRole("option", { name: /Palette fixture session/ })).toHaveAttribute("aria-selected", "true")
|
||||
|
||||
const searched = page.waitForRequest((request) => {
|
||||
const url = new URL(request.url())
|
||||
|
||||
return (
|
||||
request.method() === "GET" &&
|
||||
url.pathname === "/api/session" &&
|
||||
url.searchParams.get("search") === "Palette fixture"
|
||||
)
|
||||
})
|
||||
|
||||
// A burst of input in one task is one pause: every keystroke must supersede the last, and only the pause searches.
|
||||
await input.evaluate((element) => {
|
||||
// SAFETY: the dialog's combobox is SearchList's own text input, which is an HTMLInputElement.
|
||||
const field = element as HTMLInputElement
|
||||
const value = "Palette fixture"
|
||||
|
||||
for (let index = 1; index <= value.length; index++) {
|
||||
field.value = value.slice(0, index)
|
||||
field.dispatchEvent(new InputEvent("input", { bubbles: true }))
|
||||
}
|
||||
})
|
||||
|
||||
const request = new URL((await searched).url())
|
||||
await expect(dialog.getByRole("option", { name: /Palette fixture session/ })).toBeVisible()
|
||||
expect(searches).toHaveLength(1)
|
||||
expect(request.searchParams.get("limit")).toBe("50")
|
||||
expect(request.searchParams.get("parentID")).toBe("null")
|
||||
expect(request.searchParams.get("archived")).toBe("false")
|
||||
expect(request.searchParams.get("cursor")).toBeNull()
|
||||
})
|
||||
|
||||
test("titlebar search shows one server's matches while another server's search fails", async ({ page }) => {
|
||||
await mockRemoteServer(page, { name: "Remote" })
|
||||
const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||
|
||||
@@ -16,7 +16,12 @@ import {
|
||||
} from "solid-js"
|
||||
import { notifySessionTabsRemoved } from "@/shell/titlebar/session-events"
|
||||
import { useCommand } from "@/shell/commands/command"
|
||||
import { HOME_SESSION_LIMIT, mergeHomeSessionIndex, retainHomeSessions } from "@/home/sessions/index"
|
||||
import {
|
||||
HOME_SESSION_INDEX_LIMIT,
|
||||
HOME_SESSION_LIMIT,
|
||||
mergeHomeSessionIndex,
|
||||
retainHomeSessions,
|
||||
} from "@/home/sessions/index"
|
||||
import type { LocalProject } from "@/shell/state/layout"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { ServerConnection } from "@/runtime/server/registry"
|
||||
@@ -229,6 +234,43 @@ export function createHomeSessionsController(home: HomeController) {
|
||||
return (conn && queryClient.getQueryData<SessionInfo[]>(["home-sessions", conn])) || []
|
||||
})
|
||||
|
||||
// The shared index holds one bounded page of the newest sessions. A project scoped to older history asks the server
|
||||
// for that directory's newest sessions directly, so selecting a quiet project still lists its sessions.
|
||||
const [scopedSessions, setScopedSessions] = createSignal<SessionInfo[]>([])
|
||||
let scopedKey: string | undefined
|
||||
|
||||
createEffect(() => {
|
||||
const directories = projectDirectories()
|
||||
const conn = home.server.focused()
|
||||
const ctx = home.server.focusedContext()
|
||||
|
||||
if (!directories || !conn || !ctx) {
|
||||
scopedKey = undefined
|
||||
setScopedSessions([])
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const key = `${ServerConnection.key(conn)}\0${directories.map(pathKey).join("\0")}`
|
||||
|
||||
if (key === scopedKey) return
|
||||
scopedKey = key
|
||||
const controller = new AbortController()
|
||||
setScopedSessions([])
|
||||
void Promise.allSettled(
|
||||
directories.map((directory) =>
|
||||
ctx.sdk.api.session.list(
|
||||
{ directory, limit: HOME_SESSION_INDEX_LIMIT, order: "desc", parentID: null },
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
),
|
||||
).then((results) => {
|
||||
if (controller.signal.aborted) return
|
||||
setScopedSessions(results.flatMap((result) => (result.status === "fulfilled" ? result.value.data : [])))
|
||||
})
|
||||
onCleanup(() => controller.abort())
|
||||
})
|
||||
|
||||
const indexedSessions = createMemo(() => {
|
||||
const ctx = home.server.focusedContext()
|
||||
const conn = home.server.focused()
|
||||
@@ -236,7 +278,9 @@ export function createHomeSessionsController(home: HomeController) {
|
||||
if (!ctx || !conn) return []
|
||||
|
||||
return retainHomeSessions(
|
||||
ctx.data.session.apply(mergeHomeSessionIndex(fetchedSessions(), ctx.data.session.list())),
|
||||
ctx.data.session.apply(
|
||||
mergeHomeSessionIndex([...fetchedSessions(), ...scopedSessions()], ctx.data.session.list()),
|
||||
),
|
||||
HOME_SESSION_LIMIT,
|
||||
Date.now(),
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ import { SESSION_RECENT_LIMIT, SESSION_RECENT_WINDOW } from "@/runtime/server/gl
|
||||
import {
|
||||
HOME_SESSION_INDEX_LIMIT,
|
||||
HOME_SESSION_LIMIT,
|
||||
HOME_V2_SESSION_PAGE_LIMIT,
|
||||
HOME_SESSION_PAGE_LIMIT,
|
||||
loadHomeSessionIndex,
|
||||
mergeHomeSessionIndex,
|
||||
parseHomeSessionIndex,
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "./index"
|
||||
|
||||
const session = (id: string, input: Partial<SessionInfo> = {}) =>
|
||||
// SAFETY: fixtures spell every other field of the info they model, and each test only reads those fields.
|
||||
({
|
||||
id,
|
||||
projectID: "project",
|
||||
@@ -39,39 +40,33 @@ const history = (directory: string, count: number) =>
|
||||
const ids = (sessions: SessionInfo[]) => sessions.map((item) => item.id)
|
||||
|
||||
describe("Home session index", () => {
|
||||
test("follows cursors across pages and bounds the result per directory", async () => {
|
||||
const all = history("/repo", HOME_V2_SESSION_PAGE_LIMIT + 1)
|
||||
const calls: Array<{ cursor?: string; parentID: null }> = []
|
||||
test("loads one bounded page of the newest sessions", async () => {
|
||||
const all = history("/repo", HOME_SESSION_PAGE_LIMIT + 1)
|
||||
const calls: Array<{ limit: number; order: "desc"; cursor?: string; parentID: null }> = []
|
||||
|
||||
const result = await loadHomeSessionIndex(async (input) => {
|
||||
calls.push(input)
|
||||
|
||||
if (!input.cursor) return { data: all.slice(0, HOME_V2_SESSION_PAGE_LIMIT), cursor: { next: "next" } }
|
||||
|
||||
return { data: all.slice(HOME_V2_SESSION_PAGE_LIMIT), cursor: {} }
|
||||
return { data: all.slice(0, input.limit), cursor: { next: "next" } }
|
||||
})
|
||||
|
||||
expect(calls.map((call) => call.cursor)).toEqual([undefined, "next"])
|
||||
expect(calls.every((call) => call.parentID === null)).toBe(true)
|
||||
expect(calls).toEqual([{ limit: HOME_SESSION_PAGE_LIMIT, order: "desc", parentID: null }])
|
||||
// Newest rows in server order, plus the recent window beyond the limit.
|
||||
expect(ids(result)).toEqual(ids(all.slice(0, HOME_SESSION_INDEX_LIMIT + SESSION_RECENT_LIMIT)))
|
||||
})
|
||||
|
||||
test("folds pages so every directory keeps its newest sessions", async () => {
|
||||
const busy = history("/busy", HOME_V2_SESSION_PAGE_LIMIT + 300)
|
||||
test("keeps each directory's newest sessions within the page", async () => {
|
||||
const busy = history("/busy", 300)
|
||||
|
||||
const quiet = history("/quiet", 3).map((item) => ({
|
||||
...item,
|
||||
time: { created: item.time.created - 6000 * minute, updated: item.time.updated - 6000 * minute },
|
||||
}))
|
||||
|
||||
// Server order is global by updated time: /quiet is older than all of /busy
|
||||
// and only arrives on the second page.
|
||||
const result = await loadHomeSessionIndex(async (input) => {
|
||||
if (!input.cursor) return { data: busy.slice(0, HOME_V2_SESSION_PAGE_LIMIT), cursor: { next: "next" } }
|
||||
|
||||
return { data: [...busy.slice(HOME_V2_SESSION_PAGE_LIMIT), ...quiet], cursor: {} }
|
||||
})
|
||||
const result = await loadHomeSessionIndex(async (input) => ({
|
||||
data: [...busy.slice(0, input.limit - quiet.length), ...quiet],
|
||||
cursor: { next: "next" },
|
||||
}))
|
||||
|
||||
expect(ids(result.filter((item) => item.location.directory === "/quiet"))).toEqual(ids(quiet))
|
||||
expect(ids(result.filter((item) => item.location.directory === "/busy"))).toEqual(
|
||||
|
||||
@@ -2,7 +2,9 @@ import type { SessionInfo, SessionsResponse } from "@opencode/client/promise"
|
||||
import { pathKey } from "@/workspaces/path-key"
|
||||
import { SESSION_RECENT_LIMIT, SESSION_RECENT_WINDOW } from "@/runtime/server/global-sync/types"
|
||||
|
||||
export const HOME_V2_SESSION_PAGE_LIMIT = 5_000
|
||||
// One bounded page of the newest root sessions. Home shows 64 and the sidebar a handful per project, so older history
|
||||
// is reached through the titlebar's server-backed search instead of downloading every session on startup.
|
||||
export const HOME_SESSION_PAGE_LIMIT = 500
|
||||
|
||||
export const HOME_SESSION_LIMIT = 64
|
||||
|
||||
@@ -25,34 +27,14 @@ export async function loadHomeSessionIndex(
|
||||
) => Promise<SessionsResponse>,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const now = Date.now()
|
||||
let retained: SessionInfo[] = []
|
||||
let cursor: string | undefined
|
||||
const response = await list({ limit: HOME_SESSION_PAGE_LIMIT, order: "desc", parentID: null }, { signal })
|
||||
|
||||
for (;;) {
|
||||
const response = await list(
|
||||
{
|
||||
limit: HOME_V2_SESSION_PAGE_LIMIT,
|
||||
order: "desc",
|
||||
parentID: null,
|
||||
...(cursor ? { cursor } : {}),
|
||||
},
|
||||
{ signal },
|
||||
)
|
||||
|
||||
// Fold each page in as it arrives: pages are newest first, so later pages
|
||||
// can only fill directories that still have room. Peak allocation is one
|
||||
// page plus the retained subset, not the whole history.
|
||||
retained = retainHomeSessions([...retained, ...parseHomeSessionIndex(response.data)], HOME_SESSION_INDEX_LIMIT, now)
|
||||
|
||||
if (response.data.length < HOME_V2_SESSION_PAGE_LIMIT || !response.cursor.next) return retained
|
||||
cursor = response.cursor.next
|
||||
}
|
||||
return retainHomeSessions(parseHomeSessionIndex(response.data), HOME_SESSION_INDEX_LIMIT, Date.now())
|
||||
}
|
||||
|
||||
// Keep this filter for locally known sessions merged into the fetched index.
|
||||
export function parseHomeSessionIndex(sessions: SessionInfo[]) {
|
||||
return sessions.filter((session) => !session.parentID && typeof session.time.archived !== "number")
|
||||
return sessions.filter((session) => !session.parentID && session.time.archived === undefined)
|
||||
}
|
||||
|
||||
export function mergeHomeSessionIndex(fetched: SessionInfo[], known: SessionInfo[]) {
|
||||
|
||||
@@ -2,7 +2,6 @@ import { getFilename } from "@opencode/util/path"
|
||||
import type { Project } from "@/runtime/server/types"
|
||||
import type { SessionInfo } from "@opencode/client/promise"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { useQueryClient } from "@tanstack/solid-query"
|
||||
import { createMemo, createSignal, onCleanup, untrack, type Accessor } from "solid-js"
|
||||
import { commandPaletteOptions, useCommand, type CommandOption } from "@/shell/commands/command"
|
||||
import { useFile } from "@/workspaces/files/model"
|
||||
@@ -20,7 +19,6 @@ import { usePluginAttachment } from "@/runtime/plugin/host-apis"
|
||||
import { looksLikeSessionID } from "@/session/search"
|
||||
import { createSettingsPaletteEntries } from "@/settings/palette"
|
||||
import type { SettingsSearchResult } from "@/settings/search-results"
|
||||
import { matchesCommandPaletteEntry } from "./search"
|
||||
import {
|
||||
INITIAL_PALETTE_HIGHLIGHT_STATE,
|
||||
transitionPaletteHighlight,
|
||||
@@ -434,33 +432,29 @@ export function createServerSessionEntries(props: {
|
||||
search,
|
||||
items(text: string) {
|
||||
const search = text.trim()
|
||||
const all = entries(known(), search)
|
||||
|
||||
if (!search) return all.slice(0, props.recentLimit ?? ENTRY_LIMIT)
|
||||
if (!search) return entries(known().slice(0, props.recentLimit ?? ENTRY_LIMIT), search)
|
||||
|
||||
return all.filter((entry) => matchesCommandPaletteEntry(entry, search)).slice(0, 50)
|
||||
// The server matches titles, so narrow the loaded sessions before building entries for them. Building an entry
|
||||
// per known session on every keystroke is what made search slow once the loaded index grew.
|
||||
const value = search.toLowerCase()
|
||||
|
||||
const matched = known()
|
||||
.filter((session) => (session.title || props.untitled()).toLowerCase().includes(value))
|
||||
.slice(0, ENTRY_LIMIT * 10)
|
||||
|
||||
return entries(matched, search)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Sessions this client already has in its data store; the local list search narrows while the server answers. */
|
||||
export function createKnownServerSessions(context: Accessor<ServerCtx | undefined>) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return () => {
|
||||
const server = context()
|
||||
|
||||
if (!server) return []
|
||||
|
||||
// Reuse the Home index already loaded before opening the palette; do not fetch an index for search.
|
||||
const cached =
|
||||
queryClient.getQueryData<SessionInfo[]>(["home-sessions", server.sdk.server]) ??
|
||||
queryClient.getQueryData<SessionInfo[]>(["home-sessions", ServerConnection.key(server.sdk.server)]) ??
|
||||
[]
|
||||
|
||||
const merged = new Map([...cached, ...server.data.session.list()].map((session) => [session.id, session] as const))
|
||||
|
||||
return server.data.session.apply(
|
||||
[...merged.values()].filter((session) => !session.parentID && !session.time.archived),
|
||||
)
|
||||
return server.data.session.list().filter((session) => !session.parentID && !session.time.archived)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { CommandPaletteEntry } from "./palette"
|
||||
|
||||
export const PALETTE_SEARCH_TIMEOUT_MS = 10_000
|
||||
|
||||
export const PALETTE_SESSION_DEBOUNCE_MS = 100
|
||||
export const PALETTE_SESSION_DEBOUNCE_MS = 150
|
||||
|
||||
/** A source's last answer and the query it answered. */
|
||||
export type PaletteSearchSettled = {
|
||||
|
||||
Reference in New Issue
Block a user