diff --git a/packages/app/e2e/regression/multi-server.spec.ts b/packages/app/e2e/regression/multi-server.spec.ts
index 7703ff343d4..e74d608eb76 100644
--- a/packages/app/e2e/regression/multi-server.spec.ts
+++ b/packages/app/e2e/regression/multi-server.spec.ts
@@ -1,5 +1,15 @@
import { expect, test, type Page } from "@playwright/test"
-import { REMOTE_SERVER, SERVER, expectPath, project, seed, session, sessionHref, type TabSeed } from "../utils/app"
+import {
+ REMOTE_SERVER,
+ SERVER,
+ expectPath,
+ holdRoute,
+ project,
+ seed,
+ session,
+ sessionHref,
+ type TabSeed,
+} from "../utils/app"
import { mockServers, type MockServerConfig } from "../utils/mock-server"
import { expectSessionTitle } from "../utils/waits"
@@ -151,7 +161,9 @@ test("a remote session whose server signed the app out asks to sign in again, th
})
await seed(page, {
storage: {
- "opencode.global.dat:server": { list: [{ type: "http", http: { url: REMOTE_SERVER, password: "old-password" } }] },
+ "opencode.global.dat:server": {
+ list: [{ type: "http", http: { url: REMOTE_SERVER, password: "old-password" } }],
+ },
},
})
await page.goto(sessionHref(sessionB.id, REMOTE_SERVER))
@@ -176,6 +188,55 @@ test("a remote session whose server signed the app out asks to sign in again, th
await expect(signedOut).toHaveCount(0)
})
+// The session route waits this long for an uncached session before it calls the server unreachable.
+const RESOLUTION_TIMEOUT_MS = 30_000
+
+// How often the app checks each server's health.
+const SERVER_HEALTH_POLL_MS = 10_000
+
+test("a session its server never answers for says the server is unreachable, then opens", async ({ page }) => {
+ const late = session({ id: "ses_server_a_late", directory: directoryA, title: "Late session" })
+ const sessions = [sessionA]
+ await setup(page, { tabs: [], a: { sessions } })
+ const metadata = await holdRoute(page, new RegExp(`/api/session/${late.id}(\\?|$)`), { method: "GET" })
+ await page.clock.install()
+ await page.goto(sessionHref(late.id))
+ await metadata.arrived
+ const unreachable = page.getByText("Can't reach this server", { exact: true })
+ await expect(unreachable).toHaveCount(0)
+
+ await page.clock.fastForward(RESOLUTION_TIMEOUT_MS)
+ await expect(unreachable).toBeVisible()
+ await expect(page.getByRole("button", { name: "Close Tab", exact: true })).toBeVisible()
+
+ // The request that hung still fills the cache when it answers.
+ sessions.push(late)
+ metadata.release()
+ await expectSessionTitle(page, late.title)
+ await expect(unreachable).toHaveCount(0)
+})
+
+test("an open session stays visible while its server stops answering", async ({ page }) => {
+ const late = session({ id: "ses_server_a_late", directory: directoryA, title: "Late session" })
+ await setup(page, { tabs: [sessionA.id, late.id], a: { sessions: [sessionA] } })
+ await holdRoute(page, new RegExp(`/api/session/${late.id}(\\?|$)`), { method: "GET" })
+ await page.clock.install()
+ await page.goto(sessionHref(sessionA.id))
+ await expectSessionTitle(page, sessionA.title)
+
+ await page.route(`${SERVER}/api/info`, (route) => route.fulfill({ status: 503, body: "" }))
+ await page.clock.fastForward(SERVER_HEALTH_POLL_MS)
+ const unreachable = page.getByText("Can't reach this server", { exact: true })
+
+ // An uncached session on the same server proves the app now considers the server down.
+ await page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(late.id)}"])`).click()
+ await expect(unreachable).toBeVisible()
+
+ await page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(sessionA.id)}"])`).click()
+ await expectSessionTitle(page, sessionA.title)
+ await expect(unreachable).toHaveCount(0)
+})
+
test("auto-accept responds for an unfocused server session and its child", async ({ page }) => {
const view = await setup(page, { tabs: [sessionA.id, { session: sessionB.id, server: REMOTE_SERVER }] })
await page.goto(sessionHref(sessionA.id))
diff --git a/packages/app/e2e/regression/settings-wsl.spec.ts b/packages/app/e2e/regression/settings-wsl.spec.ts
index 849ca540ba7..5f87de494d5 100644
--- a/packages/app/e2e/regression/settings-wsl.spec.ts
+++ b/packages/app/e2e/regression/settings-wsl.spec.ts
@@ -1,6 +1,6 @@
import { base64Encode } from "@opencode/util/encode"
import { expect, test } from "@playwright/test"
-import { NO_PROVIDER, REMOTE_SERVER, SERVER, project, provider, session } from "../utils/app"
+import { NO_PROVIDER, REMOTE_SERVER, SERVER, holdRoute, project, provider, session } from "../utils/app"
import { mockOpenCodeServer, mockServers } from "../utils/mock-server"
import { expectSessionTitle } from "../utils/waits"
@@ -250,3 +250,43 @@ test("an open session moves to the controller a new SSH sign-in creates", async
await editor.press("Enter")
await expect.poll(() => prompts).toEqual(["after sign-in"])
})
+
+test("a session being created on an SSH host that turns out incompatible says so", async ({ page }) => {
+ const directory = "/home/box/project"
+ const box = session({ id: "ses_ssh_incompatible", directory, title: "SSH incompatible session" })
+
+ const config = {
+ directory,
+ project: project({ id: "proj_ssh_incompatible", directory }),
+ provider: provider(),
+ sessions: [box],
+ pageMessages: () => ({ items: [] }),
+ }
+
+ await mockServers(page, { [SERVER]: { ...config, sessions: [] }, [REMOTE_SERVER]: config })
+ const path = `/server/${base64Encode("ssh:box")}/session/${box.id}`
+ await page.goto(
+ `/e2e/utils/settings-wsl.html?${new URLSearchParams({ server: SERVER, mode: "ready", ssh: REMOTE_SERVER, path })}`,
+ )
+ await expectSessionTitle(page, box.title)
+ await page.getByRole("button", { name: "New session", exact: true }).click()
+
+ // The create request stays in flight, so the new session stays in preparation.
+ await holdRoute(page, new RegExp(`^${REMOTE_SERVER.replace(/[.]/g, "\\.")}/api/session(\\?|$)`), { method: "POST" })
+ const editor = page.locator('[data-component="composer-editor"]')
+ const send = page.getByRole("button", { name: "Send", exact: true })
+ await expect(page.locator('[data-component="new-session"]')).toBeVisible()
+ await expect(editor).toBeEditable()
+ await editor.fill("start on the box")
+ await expect(editor).toHaveText("start on the box")
+ await expect(send).toBeEnabled()
+ await send.click()
+ const preparing = page.locator('[data-component="session-preparing"]')
+ await expect(preparing).toBeVisible()
+
+ // The SSH plugin covers a host that is not ready; the route stays mounted beneath its cover.
+ await page.getByRole("button", { name: "Report incompatible SSH server" }).click()
+ await expect(page.getByRole("heading", { name: "SSH connection inactive", exact: true })).toBeVisible()
+ await expect(page.getByText("This server version isn't supported", { exact: true })).toBeAttached()
+ await expect(preparing).toHaveCount(0)
+})
diff --git a/packages/app/e2e/utils/settings-wsl.fixture.tsx b/packages/app/e2e/utils/settings-wsl.fixture.tsx
index d40fba4308a..fd2491b1066 100644
--- a/packages/app/e2e/utils/settings-wsl.fixture.tsx
+++ b/packages/app/e2e/utils/settings-wsl.fixture.tsx
@@ -299,6 +299,16 @@ export function mount(input: {
>
Require SSH sign-in
+ {/* The remote server answering with a version this app does not support. */}
+
diff --git a/packages/app/src/session/resolution-machine.test.ts b/packages/app/src/session/resolution-machine.test.ts
index 928eafe8b43..f903a1f4452 100644
--- a/packages/app/src/session/resolution-machine.test.ts
+++ b/packages/app/src/session/resolution-machine.test.ts
@@ -2,8 +2,12 @@ import { expect, test } from "bun:test"
import type { ServerHealth } from "@/runtime/server/health-machine"
import {
createSessionResolutionState,
+ SESSION_RESOLUTION_TIMEOUT_MS,
+ sessionDocumentTitle,
+ sessionModelDirectory,
sessionRouteView,
transitionSessionResolution,
+ viewedSessionID,
type SessionResolutionEffect,
type SessionResolutionEvent,
type SessionResolutionState,
@@ -11,33 +15,53 @@ import {
type SessionRouteView,
} from "./resolution-machine"
-type Session = { id: string }
+type Session = { id: string; title?: string; location: { directory: string } }
-type Event = SessionResolutionEvent
+type Pending = { draft: { directory: string } }
-type State = SessionResolutionState
+type Event = SessionResolutionEvent
+
+type State = SessionResolutionState
const target = (sessionID: string, scope = "server-a") => ({ scope, sessionID })
+const info = (id: string, title?: string): Session => ({ id, title, location: { directory: `/work/${id}` } })
+
+const timer = (attempt: number) => ({ type: "timer.start", attempt, delayMs: SESSION_RESOLUTION_TIMEOUT_MS }) as const
+
function open(
sessionID: string,
- input: { cached?: Session; connected?: boolean; refresh?: boolean; scope?: string } = {},
+ input: { cached?: Session; pending?: Pending; connected?: boolean; refresh?: boolean; scope?: string } = {},
): Event {
return {
type: "target.changed",
target: target(sessionID, input.scope),
+ pending: input.pending,
cached: input.cached,
connected: input.connected ?? true,
refresh: input.refresh ?? true,
}
}
-function replay(events: Event[]) {
- const initial: SessionResolutionTransition = { state: createSessionResolutionState(), effects: [] }
+function settledPending(sessionID: string, input: { cached?: Session; connected?: boolean } = {}): Event {
+ return {
+ type: "pending.changed",
+ target: target(sessionID),
+ pending: undefined,
+ cached: input.cached,
+ connected: input.connected ?? true,
+ refresh: true,
+ }
+}
+
+function replay(events: Event[], from: State = createSessionResolutionState()) {
+ const initial: SessionResolutionTransition = { state: from, effects: [] }
return events.reduce((current, event) => transitionSessionResolution(current.state, event), initial)
}
+const types = (effects: readonly SessionResolutionEffect[]) => effects.map((effect) => effect.type)
+
// The SDK rejects with the decoded response body.
const notFound = (sessionID: string) =>
JSON.parse(`{"_tag":"SessionNotFoundError","sessionID":"${sessionID}","message":"Session not found"}`)
@@ -50,19 +74,21 @@ test.each([
])("a $name session does not outlive a switch to another tab", ({ error, shown }) => {
const failed = replay([open("ses_a"), { type: "sync.failed", target: target("ses_a"), attempt: 1, error }])
expect(sessionRouteView(failed.state, undefined)).toMatchObject({ type: shown, sessionID: "ses_a" })
+ expect(failed.effects).toEqual([{ type: "timer.clear" }])
const next = transitionSessionResolution(failed.state, open("ses_b"))
expect(sessionRouteView(next.state, undefined)).toEqual({ type: "resolving", sessionID: "ses_b" })
expect(next.effects).toEqual([
{ type: "sync.transcript", target: target("ses_b") },
{ type: "sync.metadata", target: target("ses_b"), attempt: 2 },
+ timer(2),
])
- const cached = transitionSessionResolution(failed.state, open("ses_b", { cached: { id: "ses_b" } }))
+ const cached = transitionSessionResolution(failed.state, open("ses_b", { cached: info("ses_b") }))
expect(sessionRouteView(cached.state, undefined)).toEqual({
type: "ready",
sessionID: "ses_b",
- session: { id: "ses_b" },
+ session: info("ses_b"),
})
})
@@ -73,7 +99,9 @@ test("ignores results from an earlier visit to the same session", () => {
const late: Event[] = [
{ type: "sync.failed", target: target("ses_a"), attempt: 1, error: new Error("boom") },
{ type: "sync.settled", target: target("ses_a"), attempt: 1, session: undefined },
- { type: "sync.settled", target: target("ses_b"), attempt: 2, session: { id: "ses_b" } },
+ { type: "sync.settled", target: target("ses_b"), attempt: 2, session: info("ses_b") },
+ { type: "resolve.timed-out", attempt: 1 },
+ { type: "resolve.timed-out", attempt: 2 },
]
late.forEach((event) => expect(transitionSessionResolution(returned.state, event).state).toBe(returned.state))
@@ -87,7 +115,7 @@ test("ignores results from an earlier visit to the same session", () => {
})
test("a replaced session store is a new target", () => {
- const ready = replay([open("ses_a", { cached: { id: "ses_a" } })])
+ const ready = replay([open("ses_a", { cached: info("ses_a") })])
const replaced = transitionSessionResolution(ready.state, open("ses_a", { scope: "server-b" }))
expect(replaced.state).toEqual({ status: "resolving", target: target("ses_a", "server-b"), attempt: 2 })
@@ -98,17 +126,26 @@ test("a replaced session store is a new target", () => {
test.each<{ name: string; event: Event; effects: SessionResolutionEffect["type"][] }>([
{
name: "a cached session without refresh loads only its transcript",
- event: open("ses_a", { cached: { id: "ses_a" }, refresh: false }),
+ event: open("ses_a", { cached: info("ses_a"), refresh: false }),
effects: ["sync.transcript"],
},
{
name: "a cached session with refresh also reloads its metadata",
- event: open("ses_a", { cached: { id: "ses_a" } }),
+ event: open("ses_a", { cached: info("ses_a") }),
effects: ["sync.transcript", "sync.metadata"],
},
- { name: "a disconnected route waits to load", event: open("ses_a", { connected: false }), effects: [] },
+ {
+ name: "a disconnected route waits to load, for a bounded time",
+ event: open("ses_a", { connected: false }),
+ effects: ["timer.start"],
+ },
+ {
+ name: "a pending session loads nothing while its promotion creates it",
+ event: open("ses_a", { pending: { draft: { directory: "/draft" } } }),
+ effects: [],
+ },
])("$name", ({ event, effects }) => {
- expect(replay([event]).effects.map((effect) => effect.type)).toEqual(effects)
+ expect(types(replay([event]).effects)).toEqual(effects)
})
test("reconnecting retries a failed session and refreshes a resolved one in place", () => {
@@ -116,16 +153,16 @@ test("reconnecting retries a failed session and refreshes a resolved one in plac
const failed = replay([open("ses_a"), { type: "sync.failed", target: target("ses_a"), attempt: 1, error: "offline" }])
const retried = transitionSessionResolution(failed.state, connected)
expect(retried.state).toEqual({ status: "resolving", target: target("ses_a"), attempt: 2 })
- expect(retried.effects.map((effect) => effect.type)).toEqual(["sync.transcript", "sync.metadata"])
+ expect(types(retried.effects)).toEqual(["sync.transcript", "sync.metadata", "timer.start"])
- const ready = replay([open("ses_a", { cached: { id: "ses_a" } })])
+ const ready = replay([open("ses_a", { cached: info("ses_a") })])
const refreshed = transitionSessionResolution(ready.state, connected)
expect(refreshed.state).toBe(ready.state)
- expect(refreshed.effects.map((effect) => effect.type)).toEqual(["sync.transcript", "sync.metadata"])
+ expect(types(refreshed.effects)).toEqual(["sync.transcript", "sync.metadata"])
})
test("a resolved session stays visible through a failed refresh until it leaves the cache", () => {
- const ready = replay([open("ses_a", { cached: { id: "ses_a" } })])
+ const ready = replay([open("ses_a", { cached: info("ses_a") })])
const failure: Event = { type: "sync.failed", target: target("ses_a"), attempt: 1, error: new Error("boom") }
expect(transitionSessionResolution(ready.state, failure).state).toBe(ready.state)
@@ -137,17 +174,207 @@ test("a resolved session stays visible through a failed refresh until it leaves
})
})
-test("unmounting ignores later results", () => {
+test("unmounting ignores later results and stops the resolution timeout", () => {
const disposed = replay([open("ses_a"), { type: "disposed" }])
expect(disposed.state).toEqual({ status: "idle", attempt: 2 })
+ expect(disposed.effects).toEqual([{ type: "timer.clear" }])
- const late: Event = { type: "sync.settled", target: target("ses_a"), attempt: 1, session: { id: "ses_a" } }
- expect(transitionSessionResolution(disposed.state, late).state).toBe(disposed.state)
+ const late: Event[] = [
+ { type: "sync.settled", target: target("ses_a"), attempt: 1, session: info("ses_a") },
+ { type: "resolve.timed-out", attempt: 1 },
+ ]
+
+ late.forEach((event) => expect(transitionSessionResolution(disposed.state, event).state).toBe(disposed.state))
+})
+
+// The route showed the preparing screen outside the machine, so a server that turned out to be incompatible while a
+// new session was being created stayed on "Creating worktree" instead of saying so.
+test("an incompatible server wins over a session that is still being prepared", () => {
+ const pending = { draft: { directory: "/draft" } }
+ const preparing = replay([open("ses_a", { pending })])
+ expect(preparing.state).toEqual({ status: "preparing", target: target("ses_a"), pending, attempt: 1 })
+
+ expect(sessionRouteView(preparing.state, { type: "checking", managed: false })).toEqual({
+ type: "preparing",
+ sessionID: "ses_a",
+ pending,
+ })
+ expect(sessionRouteView(preparing.state, { type: "incompatible" })).toEqual({
+ type: "incompatible",
+ sessionID: "ses_a",
+ })
+})
+
+// The created session reached the cache before the promotion settled, so the route briefly had both a pending
+// session and a cached one: the model picker read neither directory, and the session counted as viewed early.
+test("a prepared session stays prepared until its promotion settles, then shows without resolving", () => {
+ const pending = { draft: { directory: "/draft" } }
+ const preparing = replay([open("ses_a", { pending })])
+ const created = info("ses_a")
+
+ const early: Event[] = [
+ { type: "cache.changed", target: target("ses_a"), session: created },
+ { type: "connected", target: target("ses_a"), refresh: true },
+ { type: "pending.changed", target: target("ses_a"), pending, cached: created, connected: true, refresh: true },
+ { type: "sync.settled", target: target("ses_a"), attempt: 1, session: created },
+ ]
+
+ early.forEach((event) => {
+ const next = transitionSessionResolution(preparing.state, event)
+ expect(next.state).toBe(preparing.state)
+ expect(next.effects).toEqual([])
+ })
+ expect(sessionModelDirectory(preparing.state)).toBe("/draft")
+ expect(viewedSessionID(sessionRouteView(preparing.state, { type: "healthy" }))).toBeUndefined()
+
+ const settled = transitionSessionResolution(preparing.state, settledPending("ses_a", { cached: created }))
+ expect(settled.state).toEqual({ status: "ready", target: target("ses_a"), session: created, attempt: 2 })
+ expect(types(settled.effects)).toEqual(["sync.transcript", "sync.metadata"])
+ expect(sessionModelDirectory(settled.state)).toBe("/work/ses_a")
+ expect(viewedSessionID(sessionRouteView(settled.state, { type: "healthy" }))).toBe("ses_a")
+})
+
+test("a promotion that settles before the session is cached resolves it", () => {
+ const preparing = replay([open("ses_a", { pending: { draft: { directory: "/draft" } } })])
+ const settled = transitionSessionResolution(preparing.state, settledPending("ses_a"))
+ expect(settled.state).toEqual({ status: "resolving", target: target("ses_a"), attempt: 2 })
+ expect(settled.effects).toEqual([
+ { type: "sync.transcript", target: target("ses_a") },
+ { type: "sync.metadata", target: target("ses_a"), attempt: 2 },
+ timer(2),
+ ])
+ expect(sessionModelDirectory(settled.state)).toBeUndefined()
+})
+
+// A contributed server waiting for sign-in or stopped never answers, so an uncached session stayed blank forever.
+test.each<{ health: ServerHealth; view: SessionRouteView["type"] }>([
+ { health: { type: "auth" }, view: "signed-out" },
+ { health: { type: "unauthorized" }, view: "signed-out" },
+ { health: { type: "stopped" }, view: "unreachable" },
+])("an uncached session on a $health.type server explains it, a cached one stays", ({ health, view }) => {
+ expect(sessionRouteView(replay([open("ses_a")]).state, health)).toMatchObject({ type: view, sessionID: "ses_a" })
+ expect(sessionRouteView(replay([open("ses_a", { cached: info("ses_a") })]).state, health).type).toBe("ready")
+})
+
+// A server that answers its health check while its event stream never connects, or a metadata request that hangs,
+// left the route on a bare header with no explanation and no way to close the tab.
+test("a session that does not resolve in time shows as unreachable and recovers", () => {
+ const resolving = replay([open("ses_a", { connected: false })])
+ expect(resolving.effects).toEqual([timer(1)])
+
+ const mismatched = transitionSessionResolution(resolving.state, { type: "resolve.timed-out", attempt: 99 })
+ expect(mismatched.state).toBe(resolving.state)
+
+ const timedOut = transitionSessionResolution(resolving.state, { type: "resolve.timed-out", attempt: 1 })
+ expect(timedOut.state).toEqual({ status: "unreachable", target: target("ses_a"), attempt: 1 })
+ expect(timedOut.effects).toEqual([{ type: "timer.clear" }])
+ expect(sessionRouteView(timedOut.state, { type: "healthy" })).toEqual({ type: "unreachable", sessionID: "ses_a" })
+ expect(sessionRouteView(timedOut.state, { type: "incompatible" }).type).toBe("incompatible")
+
+ const repeated = transitionSessionResolution(timedOut.state, { type: "resolve.timed-out", attempt: 1 })
+ expect(repeated.state).toBe(timedOut.state)
+ expect(repeated.effects).toEqual([])
+
+ const reconnected = transitionSessionResolution(timedOut.state, {
+ type: "connected",
+ target: target("ses_a"),
+ refresh: true,
+ })
+
+ expect(reconnected.state).toEqual({ status: "resolving", target: target("ses_a"), attempt: 2 })
+ expect(types(reconnected.effects)).toEqual(["sync.transcript", "sync.metadata", "timer.start"])
+
+ // The request the reconnect replaced no longer answers.
+ const stale: Event = { type: "sync.failed", target: target("ses_a"), attempt: 1, error: new Error("stale") }
+ expect(transitionSessionResolution(reconnected.state, stale).state).toBe(reconnected.state)
+
+ // A request that hung past the timeout still fills the cache when it finally answers.
+ const cached = transitionSessionResolution(timedOut.state, {
+ type: "cache.changed",
+ target: target("ses_a"),
+ session: info("ses_a"),
+ })
+
+ expect(cached.state).toEqual({ status: "ready", target: target("ses_a"), session: info("ses_a"), attempt: 1 })
+ expect(cached.effects).toEqual([])
+})
+
+// The timeout used to advance the attempt, so a hung request that finally answered 404 or failed was dropped and the
+// tab kept saying the server was unreachable although it had answered.
+test.each<{ name: string; event: Event; state: State }>([
+ {
+ name: "metadata",
+ event: { type: "sync.settled", target: target("ses_a"), attempt: 1, session: info("ses_a") },
+ state: { status: "ready", target: target("ses_a"), session: info("ses_a"), attempt: 1 },
+ },
+ {
+ name: "a missing session",
+ event: { type: "sync.settled", target: target("ses_a"), attempt: 1, session: undefined },
+ state: { status: "not-found", target: target("ses_a"), attempt: 1 },
+ },
+ {
+ name: "a not-found error",
+ event: { type: "sync.failed", target: target("ses_a"), attempt: 1, error: notFound("ses_a") },
+ state: { status: "not-found", target: target("ses_a"), attempt: 1 },
+ },
+ {
+ name: "a failure",
+ event: { type: "sync.failed", target: target("ses_a"), attempt: 1, error: "boom" },
+ state: { status: "error", target: target("ses_a"), error: "boom", attempt: 1 },
+ },
+])("a request that answers with $name after the timeout decides the outcome", ({ event, state }) => {
+ const timedOut = replay([open("ses_a"), { type: "resolve.timed-out", attempt: 1 }])
+ expect(timedOut.state.status).toBe("unreachable")
+
+ const answered = transitionSessionResolution(timedOut.state, event)
+ expect(answered.state).toEqual(state)
+ expect(answered.effects).toEqual([])
+})
+
+test.each<{ name: string; event: Event }>([
+ {
+ name: "metadata arrives",
+ event: { type: "sync.settled", target: target("ses_a"), attempt: 1, session: info("ses_a") },
+ },
+ {
+ name: "metadata fails",
+ event: { type: "sync.failed", target: target("ses_a"), attempt: 1, error: new Error("x") },
+ },
+ { name: "the cache fills", event: { type: "cache.changed", target: target("ses_a"), session: info("ses_a") } },
+ {
+ name: "a promotion starts",
+ event: {
+ type: "pending.changed",
+ target: target("ses_a"),
+ pending: { draft: { directory: "/draft" } },
+ cached: undefined,
+ connected: true,
+ refresh: true,
+ },
+ },
+ {
+ name: "the route loses its target",
+ event: { type: "target.changed", target: undefined, cached: undefined, connected: false, refresh: true },
+ },
+ { name: "the route unmounts", event: { type: "disposed" } },
+])("leaving resolving when $name stops the timeout", ({ event }) => {
+ const next = transitionSessionResolution(replay([open("ses_a")]).state, event)
+ expect(next.state.status).not.toBe("resolving")
+ expect(next.effects.at(-1)).toEqual({ type: "timer.clear" })
+})
+
+test("the document title names only a shown session with a real title", () => {
+ const ready = (title?: string) => replay([open("ses_a", { cached: info("ses_a", title) })]).state
+
+ expect(sessionDocumentTitle(sessionRouteView(ready("Fix the build"), undefined))).toBe("Fix the build")
+ expect(sessionDocumentTitle(sessionRouteView(ready(), undefined))).toBeUndefined()
+ expect(sessionDocumentTitle(sessionRouteView(ready("Fix the build"), { type: "incompatible" }))).toBeUndefined()
+ expect(sessionDocumentTitle(sessionRouteView(replay([open("ses_a")]).state, undefined))).toBeUndefined()
})
const resolving: State = { status: "resolving", target: target("ses_a"), attempt: 1 }
-const resolved: State = { status: "ready", target: target("ses_a"), session: { id: "ses_a" }, attempt: 1 }
+const resolved: State = { status: "ready", target: target("ses_a"), session: info("ses_a"), attempt: 1 }
const missing: State = { status: "not-found", target: target("ses_a"), attempt: 1 }
@@ -165,14 +392,14 @@ test.each<{ name: string; health: ServerHealth; state: State; view: SessionRoute
view: "unreachable",
},
{
- name: "a running health check keeps waiting",
- health: { type: "checking", managed: true },
- state: resolving,
- view: "resolving",
+ name: "an unreachable server keeps a resolved session visible",
+ health: { type: "unreachable" },
+ state: resolved,
+ view: "ready",
},
{
- name: "a rejected credential keeps waiting",
- health: { type: "unauthorized" },
+ name: "a running health check keeps waiting",
+ health: { type: "checking", managed: true },
state: resolving,
view: "resolving",
},
diff --git a/packages/app/src/session/resolution-machine.ts b/packages/app/src/session/resolution-machine.ts
index 9d00306ae24..5f519f1f859 100644
--- a/packages/app/src/session/resolution-machine.ts
+++ b/packages/app/src/session/resolution-machine.ts
@@ -1,17 +1,30 @@
+import { isFallbackTitle } from "@opencode/util/session-title-fallback"
import { isSessionNotFoundError } from "@/runtime/server/errors"
import type { ServerHealth } from "@/runtime/server/health-machine"
+/** How long an uncached session may wait for a connection or its metadata before the route calls the server unreachable. */
+export const SESSION_RESOLUTION_TIMEOUT_MS = 30_000
+
// One routed session: its ID within the session store that resolves it. A replaced store is a new target.
export type SessionTarget = {
readonly scope: Scope
readonly sessionID: string
}
-// `attempt` correlates a metadata sync with the target it was started for: it advances whenever the
-// target changes, a reconnect retries an unresolved target, or the route unmounts, so a late result is ignored.
-export type SessionResolutionState =
+// `attempt` correlates a metadata sync and the resolution timeout with the target they were started for: it advances
+// whenever the target changes, a pending session starts or settles, a reconnect retries an unresolved target, or the
+// route unmounts, so a late result is ignored. A timeout keeps the attempt: the request it gave up on may still answer.
+// `preparing` is a new session whose tab promotion still owns its creation (`pending`); nothing loads until it settles.
+export type SessionResolutionState =
| { readonly status: "idle"; readonly attempt: number }
+ | {
+ readonly status: "preparing"
+ readonly target: SessionTarget
+ readonly pending: P
+ readonly attempt: number
+ }
| { readonly status: "resolving"; readonly target: SessionTarget; readonly attempt: number }
+ | { readonly status: "unreachable"; readonly target: SessionTarget; readonly attempt: number }
| { readonly status: "ready"; readonly target: SessionTarget; readonly session: T; readonly attempt: number }
| { readonly status: "not-found"; readonly target: SessionTarget; readonly attempt: number }
| {
@@ -21,10 +34,19 @@ export type SessionResolutionState =
readonly attempt: number
}
-export type SessionResolutionEvent =
+export type SessionResolutionEvent =
| {
readonly type: "target.changed"
readonly target: SessionTarget | undefined
+ readonly pending?: P
+ readonly cached: T | undefined
+ readonly connected: boolean
+ readonly refresh: boolean
+ }
+ | {
+ readonly type: "pending.changed"
+ readonly target: SessionTarget
+ readonly pending: P | undefined
readonly cached: T | undefined
readonly connected: boolean
readonly refresh: boolean
@@ -43,135 +65,228 @@ export type SessionResolutionEvent =
readonly attempt: number
readonly error: unknown
}
+ | { readonly type: "resolve.timed-out"; readonly attempt: number }
| { readonly type: "disposed" }
export type SessionResolutionEffect =
| { readonly type: "sync.transcript"; readonly target: SessionTarget }
| { readonly type: "sync.metadata"; readonly target: SessionTarget; readonly attempt: number }
+ | { readonly type: "timer.start"; readonly attempt: number; readonly delayMs: number }
+ | { readonly type: "timer.clear" }
-export type SessionResolutionTransition = {
- readonly state: SessionResolutionState
+export type SessionResolutionTransition = {
+ readonly state: SessionResolutionState
readonly effects: readonly SessionResolutionEffect[]
}
-export type SessionRouteView =
+export type SessionRouteView =
| { readonly type: "idle" }
| { readonly type: "incompatible"; readonly sessionID: string }
+ | { readonly type: "preparing"; readonly sessionID: string; readonly pending: P }
+ | { readonly type: "signed-out"; readonly sessionID: string }
| { readonly type: "unreachable"; readonly sessionID: string }
| { readonly type: "resolving"; readonly sessionID: string }
| { readonly type: "ready"; readonly sessionID: string; readonly session: T }
| { readonly type: "not-found"; readonly sessionID: string }
| { readonly type: "error"; readonly sessionID: string; readonly error: unknown }
-type Targeted = Exclude, { readonly status: "idle" }>
+type Targeted = Exclude, { readonly status: "idle" }>
-export function createSessionResolutionState(): SessionResolutionState {
+const NO_EFFECTS: readonly SessionResolutionEffect[] = []
+
+const IDLE_VIEW: SessionRouteView = { type: "idle" }
+
+export function createSessionResolutionState(): SessionResolutionState {
return { status: "idle", attempt: 0 }
}
-export function transitionSessionResolution(
- state: SessionResolutionState,
- event: SessionResolutionEvent,
-): SessionResolutionTransition {
+export function transitionSessionResolution(
+ state: SessionResolutionState,
+ event: SessionResolutionEvent,
+): SessionResolutionTransition {
if (event.type === "disposed") return released(state)
if (event.type === "target.changed") return targetChanged(state, event)
+ if (event.type === "resolve.timed-out") {
+ if (state.status !== "resolving" || state.attempt !== event.attempt) return unchanged(state)
+
+ // Same attempt: the metadata request still in flight may answer late, and its answer still decides the outcome.
+ return changed(state, { status: "unreachable", target: state.target, attempt: state.attempt })
+ }
+
if (state.status === "idle" || !sameTarget(state.target, event.target)) return unchanged(state)
+ if (event.type === "pending.changed") return pendingChanged(state, event)
+
+ // The tab promotion owns a preparing session: it creates the session, so neither its early cache entry nor a
+ // reconnect starts loading before the promotion settles.
+ if (state.status === "preparing") return unchanged(state)
+
if (event.type === "cache.changed") return cacheChanged(state, event.session)
if (event.type === "connected") return reconnected(state, event.refresh)
- // Only the sync started for the current attempt answers a target that is still resolving: once the
- // cache holds the session it is authoritative, and a deleted session is evicted from it.
- if (state.status !== "resolving" || state.attempt !== event.attempt) return unchanged(state)
+ // Only the sync started for the current attempt answers a target that is still resolving, or that timed out
+ // waiting for it: once the cache holds the session it is authoritative, and a deleted session is evicted from it.
+ if ((state.status !== "resolving" && state.status !== "unreachable") || state.attempt !== event.attempt) {
+ return unchanged(state)
+ }
if (event.type === "sync.settled") {
if (event.session === undefined) {
- return changed({ status: "not-found", target: state.target, attempt: state.attempt })
+ return changed(state, { status: "not-found", target: state.target, attempt: state.attempt })
}
- return changed({ status: "ready", target: state.target, session: event.session, attempt: state.attempt })
+ return changed(state, { status: "ready", target: state.target, session: event.session, attempt: state.attempt })
}
if (isSessionNotFoundError(event.error, state.target.sessionID)) {
- return changed({ status: "not-found", target: state.target, attempt: state.attempt })
+ return changed(state, { status: "not-found", target: state.target, attempt: state.attempt })
}
- return changed({ status: "error", target: state.target, error: event.error, attempt: state.attempt })
+ return changed(state, { status: "error", target: state.target, error: event.error, attempt: state.attempt })
}
-export function sessionRouteView(
- state: SessionResolutionState,
+export function sessionRouteView(
+ state: SessionResolutionState,
health: ServerHealth | undefined,
-): SessionRouteView {
- if (state.status === "idle") return { type: "idle" }
+): SessionRouteView {
+ if (state.status === "idle") return IDLE_VIEW
const sessionID = state.target.sessionID
+ // A server this app cannot talk to wins over everything, including a session that is still being created.
if (health?.type === "incompatible") return { type: "incompatible", sessionID }
+ if (state.status === "preparing") return { type: "preparing", sessionID, pending: state.pending }
+
if (state.status === "ready") return { type: "ready", sessionID, session: state.session }
if (state.status === "not-found") return { type: "not-found", sessionID }
if (state.status === "error") return { type: "error", sessionID, error: state.error }
- // Nothing is cached and an unreachable server never resolves the session, so explain instead of waiting blank.
- // Only a failed health check counts: a version mismatch has its own panel, and a rejected credential is not an outage.
- if (health?.type === "unreachable") return { type: "unreachable", sessionID }
+ // Nothing is cached and a server waiting for sign-in cannot resolve the session until the user signs in.
+ if (health?.type === "auth" || health?.type === "unauthorized") return { type: "signed-out", sessionID }
+
+ // Nothing is cached and an unreachable, stopped or silent server never resolves the session, so explain instead of
+ // waiting blank.
+ if (state.status === "unreachable" || health?.type === "unreachable" || health?.type === "stopped") {
+ return { type: "unreachable", sessionID }
+ }
return { type: "resolving", sessionID }
}
-function targetChanged(
- state: SessionResolutionState,
- event: Extract, { readonly type: "target.changed" }>,
-): SessionResolutionTransition {
+/** The directory whose models the route offers: the draft's while a new session is prepared, then the session's. */
+export function sessionModelDirectory<
+ T extends { readonly location: { readonly directory: string } },
+ Scope,
+ P extends { readonly draft: { readonly directory: string } },
+>(state: SessionResolutionState) {
+ if (state.status === "preparing") return state.pending.draft.directory
+
+ if (state.status === "ready") return state.session.location.directory
+
+ return undefined
+}
+
+/** The session the user is looking at, which only a shown session is. */
+export function viewedSessionID(view: SessionRouteView) {
+ return view.type === "ready" ? view.sessionID : undefined
+}
+
+export function sessionDocumentTitle(view: SessionRouteView) {
+ if (view.type !== "ready") return undefined
+
+ return isFallbackTitle(view.session.title) ? undefined : view.session.title
+}
+
+function targetChanged(
+ state: SessionResolutionState,
+ event: Extract, { readonly type: "target.changed" }>,
+): SessionResolutionTransition {
if (!event.target) return released(state)
if (state.status !== "idle" && sameTarget(state.target, event.target)) return unchanged(state)
const attempt = state.attempt + 1
- // Start independent reads before constructing the selected view, including when its metadata is
- // cached but its transcript has never been loaded.
- const effects = event.connected ? syncs(event.target, attempt, event.cached === undefined || event.refresh) : []
+ if (event.pending !== undefined) {
+ return changed(state, { status: "preparing", target: event.target, pending: event.pending, attempt })
+ }
- if (event.cached === undefined) return changed({ status: "resolving", target: event.target, attempt }, effects)
-
- return changed({ status: "ready", target: event.target, session: event.cached, attempt }, effects)
+ return opened(state, event.target, attempt, event)
}
-function cacheChanged(
- state: Targeted,
+function pendingChanged(
+ state: Targeted,
+ event: Extract, { readonly type: "pending.changed" }>,
+): SessionResolutionTransition {
+ if (event.pending !== undefined) {
+ if (state.status === "preparing" && state.pending === event.pending) return unchanged(state)
+
+ return changed(state, {
+ status: "preparing",
+ target: state.target,
+ pending: event.pending,
+ attempt: state.attempt + 1,
+ })
+ }
+
+ if (state.status !== "preparing") return unchanged(state)
+
+ // The promotion settled: the created session is usually cached by now, so it shows without a resolving frame.
+ return opened(state, state.target, state.attempt + 1, event)
+}
+
+// Start independent reads before constructing the selected view, including when its metadata is
+// cached but its transcript has never been loaded.
+function opened(
+ state: SessionResolutionState,
+ target: SessionTarget,
+ attempt: number,
+ input: { readonly cached: T | undefined; readonly connected: boolean; readonly refresh: boolean },
+): SessionResolutionTransition {
+ const effects = input.connected ? syncs(target, attempt, input.cached === undefined || input.refresh) : NO_EFFECTS
+
+ if (input.cached === undefined) return changed(state, { status: "resolving", target, attempt }, effects)
+
+ return changed(state, { status: "ready", target, session: input.cached, attempt }, effects)
+}
+
+function cacheChanged(
+ state: Exclude, { readonly status: "preparing" }>,
session: T | undefined,
-): SessionResolutionTransition {
+): SessionResolutionTransition {
// The viewed session stays cached, so losing it after it resolved means it was deleted, possibly by another client.
if (session === undefined) {
if (state.status !== "ready") return unchanged(state)
- return changed({ status: "not-found", target: state.target, attempt: state.attempt })
+ return changed(state, { status: "not-found", target: state.target, attempt: state.attempt })
}
if (state.status === "ready" && state.session === session) return unchanged(state)
- return changed({ status: "ready", target: state.target, session, attempt: state.attempt })
+ return changed(state, { status: "ready", target: state.target, session, attempt: state.attempt })
}
// Queued inputs ride along with the transcript so a reconnect refreshes them instead of leaving the
// pre-disconnect queue on screen. A resolved session keeps its content visible while it refreshes;
// any other target retries from scratch.
-function reconnected(state: Targeted, refresh: boolean): SessionResolutionTransition {
- if (state.status === "ready") return changed(state, syncs(state.target, state.attempt, refresh))
+function reconnected(
+ state: Exclude, { readonly status: "preparing" }>,
+ refresh: boolean,
+): SessionResolutionTransition {
+ if (state.status === "ready") return { state, effects: syncs(state.target, state.attempt, refresh) }
const attempt = state.attempt + 1
- return changed({ status: "resolving", target: state.target, attempt }, syncs(state.target, attempt, true))
+ return changed(state, { status: "resolving", target: state.target, attempt }, syncs(state.target, attempt, true))
}
-function released(state: SessionResolutionState): SessionResolutionTransition {
+function released(state: SessionResolutionState): SessionResolutionTransition {
if (state.status === "idle") return unchanged(state)
- return changed({ status: "idle", attempt: state.attempt + 1 })
+ return changed(state, { status: "idle", attempt: state.attempt + 1 })
}
// The timeline owns transcript errors, so only metadata reports back to the machine.
@@ -192,13 +307,24 @@ function sameTarget(left: SessionTarget, right: SessionTarget(
- state: SessionResolutionState,
- effects: readonly SessionResolutionEffect[] = [],
-): SessionResolutionTransition {
- return { state, effects }
+// Owns the resolution timeout: every entry into `resolving` starts it for the new attempt, and every exit clears it.
+function changed(
+ previous: SessionResolutionState,
+ next: SessionResolutionState,
+ effects: readonly SessionResolutionEffect[] = NO_EFFECTS,
+): SessionResolutionTransition {
+ if (next.status === "resolving") {
+ return {
+ state: next,
+ effects: [...effects, { type: "timer.start", attempt: next.attempt, delayMs: SESSION_RESOLUTION_TIMEOUT_MS }],
+ }
+ }
+
+ if (previous.status === "resolving") return { state: next, effects: [...effects, { type: "timer.clear" }] }
+
+ return { state: next, effects }
}
-function unchanged(state: SessionResolutionState): SessionResolutionTransition {
- return { state, effects: [] }
+function unchanged(state: SessionResolutionState): SessionResolutionTransition {
+ return { state, effects: NO_EFFECTS }
}
diff --git a/packages/app/src/session/route.tsx b/packages/app/src/session/route.tsx
index d4d64f1f010..82de0ff2057 100644
--- a/packages/app/src/session/route.tsx
+++ b/packages/app/src/session/route.tsx
@@ -6,7 +6,6 @@ import { makeEventListener } from "@solid-primitives/event-listener"
import { DataProvider } from "@opencode/session-ui/context"
import { SessionUserMessage } from "@opencode/session-ui/message"
import { TextShimmer } from "@opencode/ui/text-shimmer"
-import { isFallbackTitle } from "@opencode/util/session-title-fallback"
import { CommentsProvider } from "@/composer/comments"
import { readPromptPresentation } from "@/composer/comment-note"
import { FileProvider } from "@/workspaces/files/model"
@@ -27,9 +26,9 @@ import { ErrorPage } from "@/shell/errors/error"
import { useSessionModel } from "./model"
import { SessionPanelFrame } from "./session-frame"
import { SessionIdentityHeader } from "./session-identity-header"
-import { ServerUnavailablePanel } from "./server-unavailable-panel"
+import { ServerSignedOutPanel, ServerUnavailablePanel } from "./server-unavailable-panel"
import { SessionErrorFallback, SessionNotFoundPanel } from "./route-error"
-import { sessionRouteView } from "./resolution-machine"
+import { sessionDocumentTitle, sessionModelDirectory, sessionRouteView, viewedSessionID } from "./resolution-machine"
import { createSessionResolution } from "./session-resolution"
import { SessionScreenView } from "./screen"
import { PreparingComposer } from "./preparing-composer"
@@ -40,19 +39,100 @@ export function TargetSessionRouteContent() {
const data = useData()
const server = useServer()
const tabs = useTabs()
- const directory = createMemo(() => data.session.get(params.id)?.location.directory)
+
+ const resolution = createSessionResolution(
+ () => params.id,
+ () => data.session,
+ {
+ children: true,
+ connected: () => server.ctx.sdk.connection.status() === "connected",
+ pending: (sessionID) => tabs.pendingSession(server.key, sessionID),
+ },
+ )
+
+ const view = createMemo(() => sessionRouteView(resolution(), server.health))
+ const viewed = createMemo(() => viewedSessionID(view()))
+ const title = createMemo(() => sessionDocumentTitle(view()))
+ const modelDirectory = createMemo(() => sessionModelDirectory(resolution()))
+
+ // Kept once the session leaves `ready`: the session providers can still read it while the route
+ // swaps them out, where a narrowed value would throw a stale read.
+ const directory = createMemo((previous: string) => {
+ const current = view()
+
+ return current.type === "ready" ? current.session.location.directory : previous
+ }, "")
+
+ // Health updates rebuild the view; the preparing screen and its composer stay mounted through them.
+ const preparing = createMemo(
+ () => {
+ const current = view()
+
+ return current.type === "preparing" ? current : undefined
+ },
+ undefined,
+ { equals: (a, b) => a?.sessionID === b?.sessionID && a?.pending === b?.pending },
+ )
+
+ const failure = createMemo(() => {
+ const current = view()
+
+ return current.type === "error" ? current : undefined
+ })
+
+ const closeTab = () => tabs.removeSessionTab({ server: server.key, sessionId: params.id })
return (
<>
- params.id} />
- params.id} />
-
+
+
+
- }>
- {(pending) => }
-
+
+
+
+
+
+
+
+ {(value) => }
+
+ {/* Not keyed: the session providers stay mounted while tabs switch between resolved sessions. */}
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {(value) => (
+
+
+
+ )}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -131,75 +211,6 @@ function SessionRouteErrorBoundary(props: ParentProps<{ sessionID?: string; serv
)
}
-function ResolvedTargetSessionRoute() {
- const params = useParams<{ id: string }>()
- const server = useServer()
- const tabs = useTabs()
- const data = useData()
-
- const resolution = createSessionResolution(
- () => params.id,
- () => data.session,
- { children: true, connected: () => server.ctx.sdk.connection.status() === "connected" },
- )
-
- const view = createMemo(() => sessionRouteView(resolution(), server.health))
-
- // Kept once the session leaves `ready`: the session providers can still read it while the route
- // swaps them out, where a narrowed value would throw a stale read.
- const directory = createMemo((previous: string) => {
- const current = view()
-
- return current.type === "ready" ? current.session.location.directory : previous
- }, "")
-
- const failure = createMemo(() => {
- const current = view()
-
- return current.type === "error" ? current : undefined
- })
-
- const closeTab = () => tabs.removeSessionTab({ server: server.key, sessionId: params.id })
-
- return (
-
-
-
-
-
-
- {/* Not keyed: the session providers stay mounted while tabs switch between resolved sessions. */}
-
-
-
-
-
-
-
-
-
-
-
-
-
- {(value) => (
-
-
-
- )}
-
-
-
-
-
-
-
-
-
-
- )
-}
-
function PendingSessionState(props: { sessionID: string }) {
return (
@@ -257,18 +268,10 @@ function MarkSessionViewed(props: { sessionID: () => string | undefined }) {
}
// Browser tabs and desktop windows are otherwise indistinguishable, so name them after the open session.
-function SessionDocumentTitle(props: { sessionID: () => string }) {
- const data = useData()
-
- const title = createMemo(() => {
- const value = data.session.get(props.sessionID())?.title
-
- return isFallbackTitle(value) ? undefined : value
- })
-
+function SessionDocumentTitle(props: { title: () => string | undefined }) {
// Keyed: reads its text inside a meta effect, which would hit a stale Show accessor once the session is deleted.
return (
-
+
{(value) => {`${value} ยท OpenCode`}}
)
diff --git a/packages/app/src/session/session-resolution.ts b/packages/app/src/session/session-resolution.ts
index bceb925ba44..2ce7db60616 100644
--- a/packages/app/src/session/session-resolution.ts
+++ b/packages/app/src/session/session-resolution.ts
@@ -23,17 +23,36 @@ type SessionStore = {
// Resolution is imperative rather than a resource on purpose: a resource created here would be
// created inside the router's navigation transition, and suspending that transition deadlocks the
// URL commit and double-mounts the session header portals from the transition's shadow render.
-export function createSessionResolution(
+// `pending` names a new session whose creation another owner (the tab promotion) still runs.
+export function createSessionResolution(
sessionID: () => string | undefined,
sessions: () => SessionStore,
- options?: { children?: boolean; connected?: () => boolean },
+ options?: { children?: boolean; connected?: () => boolean; pending?: (sessionID: string) => P | undefined },
) {
- const [state, setState] = createSignal(createSessionResolutionState>())
+ const [state, setState] = createSignal(createSessionResolutionState, P>())
const connected = createMemo(() => options?.connected?.() ?? true)
// Without a live connection or child sessions to load, cached metadata is already complete.
const refresh = !!options?.children || !!options?.connected
+ let timer: ReturnType | undefined
const run = (effect: SessionResolutionEffect>) => {
+ if (effect.type === "timer.clear") {
+ clearTimeout(timer)
+ timer = undefined
+
+ return
+ }
+
+ if (effect.type === "timer.start") {
+ clearTimeout(timer)
+ timer = setTimeout(() => {
+ timer = undefined
+ dispatch({ type: "resolve.timed-out", attempt: effect.attempt })
+ }, effect.delayMs)
+
+ return
+ }
+
const store = effect.target.scope
const id = effect.target.sessionID
@@ -47,14 +66,21 @@ export function createSessionResolution(
store
.sync(id, options?.children ? { children: true } : undefined)
.then(() =>
- dispatch({ type: "sync.settled", target: effect.target, attempt: effect.attempt, session: store.get(id) }),
+ dispatch({
+ type: "sync.settled",
+ target: effect.target,
+ attempt: effect.attempt,
+ session: untrack(() => store.get(id)),
+ }),
)
.catch((error) => dispatch({ type: "sync.failed", target: effect.target, attempt: effect.attempt, error }))
}
- const dispatch = (event: SessionResolutionEvent>) => {
- const result = transitionSessionResolution(untrack(state), event)
- setState(() => result.state)
+ const dispatch = (event: SessionResolutionEvent, P>) => {
+ const previous = untrack(state)
+ const result = transitionSessionResolution(previous, event)
+
+ if (result.state !== previous) setState(() => result.state)
result.effects.forEach(run)
}
@@ -71,10 +97,33 @@ export function createSessionResolution(
}
const target = { scope: store, sessionID: id }
+ const pending = createMemo(() => options?.pending?.(id))
const cached = createMemo(() => store.get(id))
- dispatch({ type: "target.changed", target, cached: cached(), connected: connected(), refresh })
+ dispatch({
+ type: "target.changed",
+ target,
+ pending: pending(),
+ cached: cached(),
+ connected: connected(),
+ refresh,
+ })
- // Owned by this target's run, so both are disposed before the next target is dispatched.
+ // Owned by this target's run, so all are disposed before the next target is dispatched.
+ createComputed(
+ on(
+ pending,
+ (value) =>
+ dispatch({
+ type: "pending.changed",
+ target,
+ pending: value,
+ cached: untrack(cached),
+ connected: untrack(connected),
+ refresh,
+ }),
+ { defer: true },
+ ),
+ )
createComputed(on(cached, (session) => dispatch({ type: "cache.changed", target, session }), { defer: true }))
createComputed(
on(
diff --git a/packages/app/test-browser/session-resolution.test.ts b/packages/app/test-browser/session-resolution.test.ts
index fba23c798ab..93d58ca3ece 100644
--- a/packages/app/test-browser/session-resolution.test.ts
+++ b/packages/app/test-browser/session-resolution.test.ts
@@ -1,14 +1,14 @@
-import { expect, test } from "bun:test"
+import { expect, jest, test } from "bun:test"
import { createRoot, createSignal } from "solid-js"
import { createStore } from "solid-js/store"
-import type { SessionResolutionState } from "@/session/resolution-machine"
+import { SESSION_RESOLUTION_TIMEOUT_MS, type SessionResolutionState } from "@/session/resolution-machine"
import { createSessionResolution } from "@/session/session-resolution"
type Session = { id: string; directory: string }
const sessionOf = (id: string): Session => ({ id, directory: `/dir/${id}` })
-function resolved(state: SessionResolutionState) {
+function resolved(state: SessionResolutionState) {
return state.status === "ready" ? state.session : undefined
}
@@ -318,3 +318,68 @@ test("reports a deleted session as not found until the route targets another ses
dispose()
})
})
+
+// The tab promotion creates a new session and caches it before it settles; only the settled promotion loads it.
+test("a prepared session loads once its promotion settles, not when its cache entry appears", async () => {
+ await createRoot(async (dispose) => {
+ const fixture = createFixture()
+ const [pending, setPending] = createSignal<{ draft: string } | undefined>({ draft: "/draft" })
+
+ const current = createSessionResolution(
+ () => "ses_a",
+ () => fixture.sessions,
+ { children: true, pending: () => pending() },
+ )
+
+ expect(current().status).toBe("preparing")
+ fixture.settle("ses_a")
+ await flush()
+ expect(current().status).toBe("preparing")
+ expect(fixture.resolves).toEqual([])
+ expect(fixture.messages.syncs).toEqual([])
+
+ setPending(undefined)
+ expect(resolved(current())?.id).toBe("ses_a")
+ expect(fixture.resolves).toEqual(["ses_a"])
+ expect(fixture.messages.syncs).toEqual(["ses_a"])
+
+ dispose()
+ })
+})
+
+test("an uncached session that never resolves shows as unreachable, and unmounting stops the timeout", () => {
+ jest.useFakeTimers()
+
+ createRoot((dispose) => {
+ const fixture = createFixture()
+ const [connection, setConnection] = createStore({ connected: false })
+
+ const current = createSessionResolution(
+ () => "ses_a",
+ () => fixture.sessions,
+ { connected: () => connection.connected },
+ )
+
+ jest.advanceTimersByTime(SESSION_RESOLUTION_TIMEOUT_MS - 1)
+ expect(current().status).toBe("resolving")
+ jest.advanceTimersByTime(1)
+ expect(current().status).toBe("unreachable")
+
+ // A reconnect retries with a fresh timeout.
+ setConnection("connected", true)
+ expect(current().status).toBe("resolving")
+ expect(fixture.resolves).toEqual(["ses_a"])
+ jest.advanceTimersByTime(SESSION_RESOLUTION_TIMEOUT_MS - 1)
+ expect(current().status).toBe("resolving")
+ jest.advanceTimersByTime(1)
+ expect(current().status).toBe("unreachable")
+
+ setConnection("connected", false)
+ setConnection("connected", true)
+ dispose()
+ jest.advanceTimersByTime(SESSION_RESOLUTION_TIMEOUT_MS)
+ expect(current().status).toBe("idle")
+ })
+
+ jest.useRealTimers()
+})