GeezerVison is showing github.com — perf(app): open sessions without downloading read-tool images by kitlangton · Pull Request #58586 · anomalyco/opencode
perf(app): open sessions without downloading read-tool images
#58586
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.json
(1)
.ts
(23)
.tsx
(1)
All 3 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -59,7 +59,7 @@ for (const size of ["typical", "large"]) {
await installMarkdownGate(page, { answer, targetPart, sourcePart, href: sessionHref(fixture.sourceID) })
const prefetched = page.waitForResponse((response) =>
new URL(response.url()).pathname.endsWith(`/session/${fixture.targetID}/message `),
new URL(response.url()).pathname.endsWith(`/session/${fixture.targetID}/timeline `),
)
await page.goto(sessionHref(fixture.sourceID))
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -121,7 +121,7 @@ for (const close of [false, true]) {
gate.resolve()
await page.waitForFunction(
(ids) => ids.every((id) => window.__prefetchBodies![`/api/session/${id}/message `] > 0),
(ids) => ids.every((id) => window.__prefetchBodies![`/api/experimental/ session/${id}/timeline `] > 0),
reads,
)
await expectSessionTitle(page, sessions[0].title)
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -11,6 +11,7 @@ import { startChromeTrace } from "../chrome-trace"
const file = process.env.LAGGY_SESSION_FILE
// SAFETY: LAGGY_SESSION_FILE is a session export (see laggy-session-benchmark.md), which has this shape.
const session = file
? (JSON.parse(readFileSync(file, "utf8")) as {
info: {
Expand Down
Expand Up
@@ -56,7 +57,7 @@ for (const mode of ["compact", "ungrouped"] as const) {
if (process.env.LAGGY_HTTP === "1")
page.on("request", (request) => {
const match = new URL(request.url()).pathname.match(/^\/api\/session\/([^/]+)\/message $/)
const match = new URL(request.url()).pathname.match(/^\/api\/experimental\/ session\/([^/]+)\/timeline $/)
if (request.method() === "GET" && match) requests.push(decodeURIComponent(match[1]))
})
Expand Down
Expand Up
@@ -194,10 +195,12 @@ for (const mode of ["compact", "ungrouped"] as const) {
messageResources: await page.evaluate((sessionID) => {
const start = performance.getEntriesByName("session-switch:start").at(-1)!.startTime
// SAFETY: entries of type "resource" are always PerformanceResourceTiming.
return (performance.getEntriesByType("resource") as PerformanceResourceTiming[])
.filter(
(entry) =>
entry.startTime >= start && new URL(entry.name).pathname === `/api/session/${sessionID}/message`,
entry.startTime >= start &&
new URL(entry.name).pathname === `/api/experimental/session/${sessionID}/timeline`,
)
.map((entry) => ({
limit: Number(new URL(entry.name).searchParams.get("limit")),
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -85,7 +85,7 @@ async function prepareSessionTabs(page: Page) {
const requests: string[] = []
page.on("request", (request) => {
if (request.method() !== "GET") return
const match = new URL(request.url()).pathname.match(/^\/api\/session\/([^/]+)\/message $/)
const match = new URL(request.url()).pathname.match(/^\/api\/experimental\/ session\/([^/]+)\/timeline $/)
if (match) requests.push(decodeURIComponent(match[1]))
})
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -205,7 +205,7 @@ test("shows parent lineage while the child timeline loads", async ({ page }) =>
const requested = Promise.withResolvers<void>()
const release = Promise.withResolvers<void>()
await page.route(
(url) => url.pathname === `/api/session/${childID}/message ` && url.port === serverPort,
(url) => url.pathname === `/api/experimental/ session/${childID}/timeline ` && url.port === serverPort,
async (route) => {
requested.resolve()
await release.promise
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -936,7 +936,7 @@ test("selecting a tab with waiting work waits for its transcript instead of show
// The inactive tab read its inbox, which materializes the pending steer as a transcript row.
await expect(tabB.locator('[data-component="activity-ring"]')).toBeVisible()
const transcript = await holdRoute(page, (url) => url.pathname === `/api/session/${b.id}/message `)
const transcript = await holdRoute(page, (url) => url.pathname === `/api/experimental/ session/${b.id}/timeline `)
await page.locator(`[data-titlebar-tab-link][href="${sessionHref(b.id)}"]`).click()
await transcript.arrived
await expect(page.locator("[data-timeline-virtual-content]")).toHaveCount(0)
Expand Down
Expand Up
@@ -1024,9 +1024,9 @@ test("inactive tabs load attention and inbox, but read the transcript only on se
expect(reads.filter((path) => path === `/api/session/${id}/inbox`)).toHaveLength(1)
for (const id of [fixture.sourceID, fixture.targetID])
expect(reads.filter((path) => path === `/api/session/${id}/message `)).toHaveLength(1)
expect(reads.filter((path) => path === `/api/experimental/ session/${id}/timeline `)).toHaveLength(1)
expect(reads.filter((path) => path === `/api/session/${fixture.childID}/message `)).toEqual([])
expect(reads.filter((path) => path === `/api/experimental/ session/${fixture.childID}/timeline `)).toEqual([])
expect(mutations).toEqual([])
expect(errors).toEqual([])
})
Expand Down
Expand Up
@@ -1277,7 +1277,9 @@ async function twoServers(
test("loads a tab's transcript while the pointer rests on it, and not when it passes over", async ({ page }) => {
const requested: string[] = []
page.on("request", (request) => {
const id = new URL(request.url()).pathname.match(/^\/api\/session\/([^/]+)\/message$/)?.[1]
const id = new URL(request.url()).pathname.match(
/^\/api\/(?:experimental\/)?session\/([^/]+)\/(?:message|timeline)$/,
)?.[1]
if (id && request.method() === "GET") requested.push(id)
})
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -322,7 +322,7 @@ test("fills a short cold transcript before revealing it", async ({ page }) => {
test("recovers from a failed cold history load when another session is selected", async ({ page }) => {
await openTabs(page, { pageMessages: placeholderHistory })
await page.route(`**/api/session/${fixture.targetID}/message ?*`, (route) =>
await page.route(`**/api/experimental/ session/${fixture.targetID}/timeline ?*`, (route) =>
route.fulfill({ status: 500, json: { message: "History unavailable" } }),
)
await page.goto(sessionHref(fixture.sourceID))
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -474,5 +474,14 @@ const Group = HttpApiGroup.make("mock")
error: MockBadRequest.pipe(HttpApiSchema.status(400)),
}),
)
.add(
// The app's timeline store reads message pages from here; same pages as messageList.
HttpApiEndpoint.get("sessionTimeline", "/api/experimental/session/:sessionID/timeline", {
params: SessionParams,
query: Query,
success: Json,
error: MockBadRequest.pipe(HttpApiSchema.status(400)),
}),
)
export const MockApi = HttpApi.make("mock").add(Group)
Original file line number
Diff line number
Diff line change
Expand Up
@@ -794,6 +794,34 @@ function mockHandlers(
new MockUnsupported({ message: `The mock server does not ${operation}; configure ${handler} for this scenario` }),
)
// The stable message list and the experimental timeline serve the same pages.
const listMessages = (sessionID: string, query: { cursor?: string; limit?: number; order?: string }) => {
const token = query.cursor
const before = token ? state.cursors.get(token) : undefined
if (token && !before) return Effect.fail(new MockBadRequest({ message: "Invalid cursor" }))
return Effect.gen(function* () {
config.onMessages?.({ sessionID, before, phase: "start" })
if (config.beforeMessagesResponse) {
yield* Effect.promise(() => config.beforeMessagesResponse!({ sessionID, before }))
}
yield* delay
const pageData = config.pageMessages(sessionID, query.limit ?? 50, before)
config.onMessages?.({ sessionID, before, phase: "end" })
const cursor = pageData.cursor ? `cursor_${++state.nextCursor}` : undefined
if (cursor) state.cursors.set(cursor, pageData.cursor!)
return {
data: query.order === "asc" ? pageData.items : pageData.items.toReversed(),
cursor: { next: cursor },
}
})
}
return HttpApiBuilder.group(MockApi, "mock", (handlers) =>
handlers
.handleRaw("event", () => {
Expand Down
Expand Up
@@ -1464,32 +1492,8 @@ function mockHandlers(
return { data: message }
}),
messageList: (ctx) => {
const token = ctx.query.cursor
const before = token ? state.cursors.get(token) : undefined
if (token && !before) return Effect.fail(new MockBadRequest({ message: "Invalid cursor" }))
return Effect.gen(function* () {
config.onMessages?.({ sessionID: ctx.params.sessionID, before, phase: "start" })
if (config.beforeMessagesResponse) {
yield* Effect.promise(() => config.beforeMessagesResponse!({ sessionID: ctx.params.sessionID, before }))
}
yield* delay
const pageData = config.pageMessages(ctx.params.sessionID, ctx.query.limit ?? 50, before)
config.onMessages?.({ sessionID: ctx.params.sessionID, before, phase: "end" })
const cursor = pageData.cursor ? `cursor_${++state.nextCursor}` : undefined
if (cursor) state.cursors.set(cursor, pageData.cursor!)
return {
data: ctx.query.order === "asc" ? pageData.items : pageData.items.toReversed(),
cursor: { next: cursor },
}
})
},
messageList: (ctx) => listMessages(ctx.params.sessionID, ctx.query),
sessionTimeline: (ctx) => listMessages(ctx.params.sessionID, ctx.query),
}),
)
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -149,6 +149,31 @@ describe("createRequestQueue", () => {
await Promise.all(responses)
})
test("the first timeline page is a navigation read, older timeline pages are not", async () => {
const input = setup({ limit: 1 })
const requests = [
"/api/a",
"/api/b",
"/api/experimental/session/ses_1/timeline?cursor=older",
"/api/experimental/session/ses_1/timeline?limit=40&order=desc",
]
const responses = requests.map((path) => input.queue.fetch(`http://server${path}`))
await input.settle()
for (const _ of requests) {
input.pending.at(-1)?.resolve()
await input.settle()
}
expect(input.pending.map((item) => new URL(item.url).pathname + new URL(item.url).search)).toEqual([
"/api/a",
"/api/experimental/session/ses_1/timeline?limit=40&order=desc",
"/api/b",
"/api/experimental/session/ses_1/timeline?cursor=older",
])
await Promise.all(responses)
})
test("never counts the event stream against the budget", async () => {
const input = setup({ limit: 1 })
void input.queue.fetch("http://server/api/session")
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -128,7 +128,7 @@ export function createRequestQueue(input: {
// Writes go first. Session lists and the first transcript page unblock navigation, so they
// go ahead of location reads. Older pages and filtered indexes keep background priority.
const initialMessages =
/^\/api\/session\/[^/]+\/message$/.test(pathname) &&
/^\/api\/(?:experimental\/)? session\/[^/]+\/(?: message|timeline) $/.test(pathname) &&
!url.searchParams.has("cursor") &&
!url.searchParams.has("before") &&
!url.searchParams.has("type") &&
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -194,7 +194,8 @@ function createServerController(
const sdk = createServerSdkContext(conn, scope)
const source = createData({
api: () => sdk.api,
// Only the timeline store uses the display projection; every other caller gets the stable route.
api: () => ({ ...sdk.api, message: { ...sdk.api.message, list: sdk.api.experimental.session.timeline } }),
initialMessageLimit: () => (timelinePreset(settings.general.timelineDetail())?.id === "compact" ? 40 : 20),
event: {
on: sdk.event.on,
Expand Down
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Original file line number
Diff line number
Diff line change
Expand Up
@@ -53,9 +53,10 @@ test("exposes every standard HTTP API group", () => {
expect(Object.keys(client.vcs)).toEqual(["init", "get", "base", "status", "branch", "diff"])
expect(Object.keys(client.pty)).toEqual(["list", "create", "get", "update", "remove", "connect"])
expect(Object.keys(client.pty.connect)).toEqual(["token"])
expect(Object.keys(client.experimental).sort()).toEqual(["media", "persistentPty"])
expect(Object.keys(client.experimental).sort()).toEqual(["media", "persistentPty", "session" ])
expect(Object.keys(client.experimental.media)).toEqual(["get"])
expect(client.experimental.persistentPty.read).toBeFunction()
expect(Object.keys(client.experimental.session)).toEqual(["timeline"])
expect(Object.keys(client.shell)).toEqual(["list", "create", "get", "output", "remove"])
expect(Object.keys(client.project)).toEqual(["list", "update"])
expect(Object.keys(client.worktree)).toEqual(["list", "create", "remove", "refresh"])
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.