Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions packages/app/e2e/regression/tabs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,42 @@ test("inactive tabs load attention and inbox, but read the transcript only on se
expect(errors).toEqual([])
})

test("closing a tab releases its transcript, and reopening it reads the transcript again", async ({ page }) => {
const reads: string[] = []
const errors: string[] = []
page.on("pageerror", (error) => errors.push(error.message))
page.on("request", (request) => {
if (request.method() === "GET") reads.push(new URL(request.url()).pathname)
})
const history = (id: string) =>
page.locator(`[data-timeline-row="UserMessage"][data-message-id="msg_${id}_history"]`)
await openSession(page, {
name: "TabRetention",
sessions: [a, b],
pageMessages: (id) => ({
items: [{ id: `msg_${id}_history`, type: "user", text: `History of ${id}`, time: { created: 1 } }],
}),
})
await expect(history(a.id)).toContainText(`History of ${a.id}`)

await page.locator(`[data-titlebar-tab-link][href="${sessionHref(b.id)}"]`).click()
await expect(history(b.id)).toContainText(`History of ${b.id}`)
await page.keyboard.press("Control+w")
await expect(page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(b.id)}"])`)).toHaveCount(0)
await expectSessionTitle(page, a.title)

// A release has no visible signal, so wait past the retention delay. The open tab keeps its transcript.
await page.waitForTimeout(2_000)
await expect(history(a.id)).toContainText(`History of ${a.id}`)

await page.keyboard.press("Control+Shift+T")
await expectSessionTitle(page, b.title)
await expect(history(b.id)).toContainText(`History of ${b.id}`)
await expect.poll(() => reads.filter((path) => path === `/api/session/${b.id}/message`).length).toBe(2)
expect(reads.filter((path) => path === `/api/session/${a.id}/message`)).toHaveLength(1)
expect(errors).toEqual([])
})

test("five loaded workspace tabs stay rendered and reactive through repeated switches", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })

Expand Down
41 changes: 40 additions & 1 deletion packages/app/src/runtime/server/runtime.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import { createSimpleContext } from "@opencode/ui/context"
import { Accessor, batch, createEffect, createMemo, createResource, createRoot, getOwner, untrack } from "solid-js"
import {
Accessor,
batch,
createEffect,
createMemo,
createResource,
createRoot,
getOwner,
untrack,
useTransition,
} from "solid-js"
import { useLocation } from "@solidjs/router"
import { createServerProjects, RECENTLY_CLOSED_DISPLAY_LIMIT, ServerConnection, useServers } from "./registry"
import { createSessionRetention } from "./session-retention"
import { sessionHref } from "@/shell/routes/session"
import { useTabs } from "@/shell/tabs/tabs"
import { pathKey } from "@/workspaces/path-key"
import { useServerHealth } from "@/runtime/server/health"
import { createServerSdkContext } from "./client"
Expand Down Expand Up @@ -198,6 +212,31 @@ function createServerController(
createPermissionAutoApprover({ sdk, data })
const notification = createServerNotificationState({ sdk, data, key: connKey, coordinator: notificationCoordinator })

const tabs = useTabs()
const location = useLocation()
// Parsed here because the shared route parser throws on routes it does not recognise.
const routes = sessionHref(connKey, "")
createSessionRetention({
session: data.session,
ready: tabs.ready,
visible: () => {
const routed = location.pathname.startsWith(routes)
? location.pathname.slice(routes.length).split("/")[0]
: undefined
return [
...(routed ? [routed] : []),
...tabs.store.flatMap((tab) =>
tab.type === "session" && tab.server === connKey
? [tab.sessionId, tab.routeSessionId, tab.routeParentId].flatMap((id) => (id ? [id] : []))
: [],
),
]
},
navigating: useTransition()[0],
// Covers an open path whose transcript read lands before the transition adding its tab commits.
delay: 1_000,
})

function enrich(project: { worktree: string; expanded: boolean }) {
const [childStore] = sync.child(project.worktree, { bootstrap: false })
const projectID = childStore.project
Expand Down
62 changes: 62 additions & 0 deletions packages/app/src/runtime/server/session-retention.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { createEffect, onCleanup, type Accessor } from "solid-js"
import type { Data } from "@opencode/client/solid"

type Session = Pick<Data["session"], "cached" | "root" | "evict" | "active" | "permission" | "form">

/**
* Releases the cached transcripts of session families that no open tab, session route, running work or attention
* request keeps. A family is released once it has stayed unkept for `delay` with no transition pending, since an open
* path can read a transcript before the transition that adds its tab or route commits. Late reads and events that
* bring rows back to a released family start a new delay, so they cannot keep it cached.
*/
export function createSessionRetention(input: {
session: Session
/** Persisted tabs have loaded. */
ready: Accessor<boolean>
/** Sessions shown by open tabs or the current route. */
visible: Accessor<readonly string[]>
navigating: Accessor<boolean>
delay: number
}) {
const timers = new Map<string, ReturnType<typeof setTimeout>>()
onCleanup(() => timers.forEach((timer) => clearTimeout(timer)))
const unkept = () => new Set(input.ready() && !input.navigating() ? unkeptRoots(input.session, input.visible()) : [])

const release = (root: string) => {
timers.set(
root,
setTimeout(() => {
timers.delete(root)
input.session.evict(root)
// Eviction keeps unacknowledged submissions and sessions still being created, and settling them need not
// change the cached set this policy tracks. Retry while the family stays unkept and cached.
if (!timers.has(root) && unkept().has(root)) release(root)
}, input.delay),
)
}

createEffect(() => {
const roots = unkept()
timers.forEach((timer, root) => {
if (roots.has(root)) return
clearTimeout(timer)
timers.delete(root)
})
// A family that keeps receiving rows still releases at its first deadline.
roots.forEach((root) => {
if (!timers.has(root)) release(root)
})
})
}

function unkeptRoots(session: Session, visible: readonly string[]) {
const kept = new Set(
[...visible, ...session.active(), ...session.permission.sessions(), ...session.form.sessions()].map((id) =>
session.root(id),
),
)
return session
.cached()
.map((id) => session.root(id))
.filter((root) => !kept.has(root))
}
Loading
Loading