mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 05:01:03 +03:00
fix(app): reset the session route when switching tabs after a session error (#61585)
This commit is contained in:
committed by
GitHub
Unverified
parent
0c441474bd
commit
3d051d6fb7
@@ -1,3 +1,5 @@
|
||||
import { Predicate } from "effect"
|
||||
|
||||
export type ConfigInvalidError = {
|
||||
name: "ConfigInvalidError"
|
||||
data: {
|
||||
@@ -27,73 +29,67 @@ function tr(translator: Translator | undefined, key: string, text: string, vars?
|
||||
return out
|
||||
}
|
||||
|
||||
export function formatServerError(error: unknown, translate?: Translator, fallback?: string) {
|
||||
const unwrapped = unwrapNamedError(error)
|
||||
export function formatServerError(cause: unknown, translate?: Translator, fallback?: string) {
|
||||
const unwrapped = unwrapNamedError(cause)
|
||||
|
||||
if (isConfigInvalidErrorLike(unwrapped)) return parseReadableConfigInvalidError(unwrapped, translate)
|
||||
|
||||
if (isProviderModelNotFoundErrorLike(unwrapped)) return parseReadableProviderModelNotFoundError(unwrapped, translate)
|
||||
|
||||
if (
|
||||
typeof unwrapped === "object" &&
|
||||
unwrapped !== null &&
|
||||
"message" in unwrapped &&
|
||||
typeof unwrapped.message === "string" &&
|
||||
Predicate.isObjectOrArray(unwrapped) &&
|
||||
Predicate.hasProperty(unwrapped, "message") &&
|
||||
Predicate.isString(unwrapped.message) &&
|
||||
unwrapped.message
|
||||
)
|
||||
return unwrapped.message
|
||||
|
||||
if (error instanceof Error && error.message) return error.message
|
||||
if (cause instanceof Error && cause.message) return cause.message
|
||||
|
||||
if (typeof error === "string" && error) return error
|
||||
if (Predicate.isString(cause) && cause) return cause
|
||||
|
||||
if (fallback) return fallback
|
||||
|
||||
return tr(translate, "error.chain.unknown", "Unknown error")
|
||||
}
|
||||
|
||||
function unwrapNamedError(error: unknown): unknown {
|
||||
if (!(error instanceof Error) || !error.cause || typeof error.cause !== "object") return error
|
||||
function unwrapNamedError(cause: unknown) {
|
||||
if (!(cause instanceof Error) || !Predicate.isObjectOrArray(cause.cause)) return cause
|
||||
|
||||
if ("body" in error.cause) return (error.cause as Record<string, unknown>).body
|
||||
if (Predicate.hasProperty(cause.cause, "body")) return cause.cause.body
|
||||
|
||||
return error.cause
|
||||
return cause.cause
|
||||
}
|
||||
|
||||
// Client-synthesized session not-found errors share one constructor and
|
||||
// predicate so the message contract cannot drift between route session
|
||||
// resolution (session-resolution.ts) and not-found fallback matching (session.tsx).
|
||||
const sessionNotFoundMessage = (sessionID: string) => `Session not found: ${sessionID}`
|
||||
export function isSessionNotFoundError(cause: unknown, sessionID: string) {
|
||||
const unwrapped = unwrapNamedError(cause)
|
||||
|
||||
export function sessionNotFoundError(sessionID: string) {
|
||||
return new Error(sessionNotFoundMessage(sessionID))
|
||||
}
|
||||
|
||||
export function isLocalSessionNotFoundError(error: unknown, sessionID: string) {
|
||||
return error instanceof Error && error.message === sessionNotFoundMessage(sessionID)
|
||||
}
|
||||
|
||||
export function isSessionNotFoundError(error: unknown, sessionID: string) {
|
||||
const unwrapped = unwrapNamedError(error)
|
||||
|
||||
if (typeof unwrapped !== "object" || unwrapped === null) return false
|
||||
const value = unwrapped as Record<string, unknown>
|
||||
|
||||
return value._tag === "SessionNotFoundError" && value.sessionID === sessionID
|
||||
return (
|
||||
Predicate.isObjectOrArray(unwrapped) &&
|
||||
Predicate.isTagged(unwrapped, "SessionNotFoundError") &&
|
||||
Predicate.hasProperty(unwrapped, "sessionID") &&
|
||||
unwrapped.sessionID === sessionID
|
||||
)
|
||||
}
|
||||
|
||||
function isConfigInvalidErrorLike(error: unknown): error is ConfigInvalidError {
|
||||
if (typeof error !== "object" || error === null) return false
|
||||
const o = error as Record<string, unknown>
|
||||
|
||||
return o.name === "ConfigInvalidError" && typeof o.data === "object" && o.data !== null
|
||||
return (
|
||||
Predicate.isObjectOrArray(error) &&
|
||||
Predicate.hasProperty(error, "name") &&
|
||||
error.name === "ConfigInvalidError" &&
|
||||
Predicate.hasProperty(error, "data") &&
|
||||
Predicate.isObjectOrArray(error.data)
|
||||
)
|
||||
}
|
||||
|
||||
function isProviderModelNotFoundErrorLike(error: unknown): error is ProviderModelNotFoundError {
|
||||
if (typeof error !== "object" || error === null) return false
|
||||
const o = error as Record<string, unknown>
|
||||
|
||||
return o.name === "ProviderModelNotFoundError" && typeof o.data === "object" && o.data !== null
|
||||
return (
|
||||
Predicate.isObjectOrArray(error) &&
|
||||
Predicate.hasProperty(error, "name") &&
|
||||
error.name === "ProviderModelNotFoundError" &&
|
||||
Predicate.hasProperty(error, "data") &&
|
||||
Predicate.isObjectOrArray(error.data)
|
||||
)
|
||||
}
|
||||
|
||||
export function parseReadableConfigInvalidError(errorInput: ConfigInvalidError, translator?: Translator) {
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import type { ServerHealth } from "@/runtime/server/health"
|
||||
import {
|
||||
createSessionResolutionState,
|
||||
sessionRouteView,
|
||||
transitionSessionResolution,
|
||||
type SessionResolutionEffect,
|
||||
type SessionResolutionEvent,
|
||||
type SessionResolutionState,
|
||||
type SessionResolutionTransition,
|
||||
type SessionRouteView,
|
||||
} from "./resolution-machine"
|
||||
|
||||
type Session = { id: string }
|
||||
|
||||
type Event = SessionResolutionEvent<Session, string>
|
||||
|
||||
type State = SessionResolutionState<Session, string>
|
||||
|
||||
const target = (sessionID: string, scope = "server-a") => ({ scope, sessionID })
|
||||
|
||||
function open(
|
||||
sessionID: string,
|
||||
input: { cached?: Session; connected?: boolean; refresh?: boolean; scope?: string } = {},
|
||||
): Event {
|
||||
return {
|
||||
type: "target.changed",
|
||||
target: target(sessionID, input.scope),
|
||||
cached: input.cached,
|
||||
connected: input.connected ?? true,
|
||||
refresh: input.refresh ?? true,
|
||||
}
|
||||
}
|
||||
|
||||
function replay(events: Event[]) {
|
||||
const initial: SessionResolutionTransition<Session, string> = { state: createSessionResolutionState(), effects: [] }
|
||||
|
||||
return events.reduce((current, event) => transitionSessionResolution(current.state, event), initial)
|
||||
}
|
||||
|
||||
// The SDK rejects with the decoded response body.
|
||||
const notFound = (sessionID: string) =>
|
||||
JSON.parse(`{"_tag":"SessionNotFoundError","sessionID":"${sessionID}","message":"Session not found"}`)
|
||||
|
||||
// The route used to rethrow these outcomes into an error boundary that every session tab on the
|
||||
// server shares, so the next tab kept showing the previous session's error.
|
||||
test.each([
|
||||
{ name: "missing", error: notFound("ses_a"), shown: "not-found" },
|
||||
{ name: "failed", error: new Error("boom"), shown: "error" },
|
||||
])("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" })
|
||||
|
||||
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 },
|
||||
])
|
||||
|
||||
const cached = transitionSessionResolution(failed.state, open("ses_b", { cached: { id: "ses_b" } }))
|
||||
expect(sessionRouteView(cached.state, undefined)).toEqual({
|
||||
type: "ready",
|
||||
sessionID: "ses_b",
|
||||
session: { id: "ses_b" },
|
||||
})
|
||||
})
|
||||
|
||||
test("ignores results from an earlier visit to the same session", () => {
|
||||
const returned = replay([open("ses_a"), open("ses_b"), open("ses_a")])
|
||||
expect(returned.state).toEqual({ status: "resolving", target: target("ses_a"), attempt: 3 })
|
||||
|
||||
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" } },
|
||||
]
|
||||
|
||||
late.forEach((event) => expect(transitionSessionResolution(returned.state, event).state).toBe(returned.state))
|
||||
|
||||
const current: Event = { type: "sync.settled", target: target("ses_a"), attempt: 3, session: undefined }
|
||||
expect(transitionSessionResolution(returned.state, current).state).toEqual({
|
||||
status: "not-found",
|
||||
target: target("ses_a"),
|
||||
attempt: 3,
|
||||
})
|
||||
})
|
||||
|
||||
test("a replaced session store is a new target", () => {
|
||||
const ready = replay([open("ses_a", { cached: { id: "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 })
|
||||
|
||||
const stale: Event = { type: "cache.changed", target: target("ses_a"), session: undefined }
|
||||
expect(transitionSessionResolution(replaced.state, stale).state).toBe(replaced.state)
|
||||
})
|
||||
|
||||
test.each<{ name: string; event: Event; effects: SessionResolutionEffect<string>["type"][] }>([
|
||||
{
|
||||
name: "a cached session without refresh loads only its transcript",
|
||||
event: open("ses_a", { cached: { id: "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" } }),
|
||||
effects: ["sync.transcript", "sync.metadata"],
|
||||
},
|
||||
{ name: "a disconnected route waits to load", event: open("ses_a", { connected: false }), effects: [] },
|
||||
])("$name", ({ event, effects }) => {
|
||||
expect(replay([event]).effects.map((effect) => effect.type)).toEqual(effects)
|
||||
})
|
||||
|
||||
test("reconnecting retries a failed session and refreshes a resolved one in place", () => {
|
||||
const connected: Event = { type: "connected", target: target("ses_a"), refresh: true }
|
||||
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"])
|
||||
|
||||
const ready = replay([open("ses_a", { cached: { id: "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"])
|
||||
})
|
||||
|
||||
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 failure: Event = { type: "sync.failed", target: target("ses_a"), attempt: 1, error: new Error("boom") }
|
||||
expect(transitionSessionResolution(ready.state, failure).state).toBe(ready.state)
|
||||
|
||||
const deleted: Event = { type: "cache.changed", target: target("ses_a"), session: undefined }
|
||||
expect(transitionSessionResolution(ready.state, deleted).state).toEqual({
|
||||
status: "not-found",
|
||||
target: target("ses_a"),
|
||||
attempt: 1,
|
||||
})
|
||||
})
|
||||
|
||||
test("unmounting ignores later results", () => {
|
||||
const disposed = replay([open("ses_a"), { type: "disposed" }])
|
||||
expect(disposed.state).toEqual({ status: "idle", attempt: 2 })
|
||||
|
||||
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 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 missing: State = { status: "not-found", target: target("ses_a"), attempt: 1 }
|
||||
|
||||
test.each<{ name: string; health: ServerHealth; state: State; view: SessionRouteView<Session>["type"] }>([
|
||||
{
|
||||
name: "incompatible wins over a resolved session",
|
||||
health: { healthy: true, incompatible: true },
|
||||
state: resolved,
|
||||
view: "incompatible",
|
||||
},
|
||||
{
|
||||
name: "an unreachable server explains a pending session",
|
||||
health: { healthy: false },
|
||||
state: resolving,
|
||||
view: "unreachable",
|
||||
},
|
||||
{
|
||||
name: "a running health check keeps waiting",
|
||||
health: { healthy: false, checking: true },
|
||||
state: resolving,
|
||||
view: "resolving",
|
||||
},
|
||||
{
|
||||
name: "a rejected credential keeps waiting",
|
||||
health: { healthy: false, unauthorized: true },
|
||||
state: resolving,
|
||||
view: "resolving",
|
||||
},
|
||||
{
|
||||
name: "an unreachable server keeps a known outcome",
|
||||
health: { healthy: false },
|
||||
state: missing,
|
||||
view: "not-found",
|
||||
},
|
||||
])("view: $name", ({ health, state, view }) => {
|
||||
expect(sessionRouteView(state, health).type).toBe(view)
|
||||
})
|
||||
@@ -0,0 +1,204 @@
|
||||
import { isSessionNotFoundError } from "@/runtime/server/errors"
|
||||
import type { ServerHealth } from "@/runtime/server/health"
|
||||
|
||||
// One routed session: its ID within the session store that resolves it. A replaced store is a new target.
|
||||
export type SessionTarget<Scope> = {
|
||||
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<T, Scope> =
|
||||
| { readonly status: "idle"; readonly attempt: number }
|
||||
| { readonly status: "resolving"; readonly target: SessionTarget<Scope>; readonly attempt: number }
|
||||
| { readonly status: "ready"; readonly target: SessionTarget<Scope>; readonly session: T; readonly attempt: number }
|
||||
| { readonly status: "not-found"; readonly target: SessionTarget<Scope>; readonly attempt: number }
|
||||
| {
|
||||
readonly status: "error"
|
||||
readonly target: SessionTarget<Scope>
|
||||
readonly error: unknown
|
||||
readonly attempt: number
|
||||
}
|
||||
|
||||
export type SessionResolutionEvent<T, Scope> =
|
||||
| {
|
||||
readonly type: "target.changed"
|
||||
readonly target: SessionTarget<Scope> | undefined
|
||||
readonly cached: T | undefined
|
||||
readonly connected: boolean
|
||||
readonly refresh: boolean
|
||||
}
|
||||
| { readonly type: "cache.changed"; readonly target: SessionTarget<Scope>; readonly session: T | undefined }
|
||||
| { readonly type: "connected"; readonly target: SessionTarget<Scope>; readonly refresh: boolean }
|
||||
| {
|
||||
readonly type: "sync.settled"
|
||||
readonly target: SessionTarget<Scope>
|
||||
readonly attempt: number
|
||||
readonly session: T | undefined
|
||||
}
|
||||
| {
|
||||
readonly type: "sync.failed"
|
||||
readonly target: SessionTarget<Scope>
|
||||
readonly attempt: number
|
||||
readonly error: unknown
|
||||
}
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type SessionResolutionEffect<Scope> =
|
||||
| { readonly type: "sync.transcript"; readonly target: SessionTarget<Scope> }
|
||||
| { readonly type: "sync.metadata"; readonly target: SessionTarget<Scope>; readonly attempt: number }
|
||||
|
||||
export type SessionResolutionTransition<T, Scope> = {
|
||||
readonly state: SessionResolutionState<T, Scope>
|
||||
readonly effects: readonly SessionResolutionEffect<Scope>[]
|
||||
}
|
||||
|
||||
export type SessionRouteView<T> =
|
||||
| { readonly type: "idle" }
|
||||
| { readonly type: "incompatible"; 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<T, Scope> = Exclude<SessionResolutionState<T, Scope>, { readonly status: "idle" }>
|
||||
|
||||
export function createSessionResolutionState<T, Scope>(): SessionResolutionState<T, Scope> {
|
||||
return { status: "idle", attempt: 0 }
|
||||
}
|
||||
|
||||
export function transitionSessionResolution<T, Scope>(
|
||||
state: SessionResolutionState<T, Scope>,
|
||||
event: SessionResolutionEvent<T, Scope>,
|
||||
): SessionResolutionTransition<T, Scope> {
|
||||
if (event.type === "disposed") return released(state)
|
||||
|
||||
if (event.type === "target.changed") return targetChanged(state, event)
|
||||
|
||||
if (state.status === "idle" || !sameTarget(state.target, event.target)) 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)
|
||||
|
||||
if (event.type === "sync.settled") {
|
||||
if (event.session === undefined) {
|
||||
return changed({ status: "not-found", target: state.target, attempt: state.attempt })
|
||||
}
|
||||
|
||||
return changed({ 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({ status: "error", target: state.target, error: event.error, attempt: state.attempt })
|
||||
}
|
||||
|
||||
export function sessionRouteView<T, Scope>(
|
||||
state: SessionResolutionState<T, Scope>,
|
||||
health: ServerHealth | undefined,
|
||||
): SessionRouteView<T> {
|
||||
if (state.status === "idle") return { type: "idle" }
|
||||
const sessionID = state.target.sessionID
|
||||
|
||||
if (health?.incompatible) return { type: "incompatible", sessionID }
|
||||
|
||||
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 && !health.healthy && !health.checking && !health.unauthorized) return { type: "unreachable", sessionID }
|
||||
|
||||
return { type: "resolving", sessionID }
|
||||
}
|
||||
|
||||
function targetChanged<T, Scope>(
|
||||
state: SessionResolutionState<T, Scope>,
|
||||
event: Extract<SessionResolutionEvent<T, Scope>, { readonly type: "target.changed" }>,
|
||||
): SessionResolutionTransition<T, Scope> {
|
||||
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.cached === undefined) return changed({ status: "resolving", target: event.target, attempt }, effects)
|
||||
|
||||
return changed({ status: "ready", target: event.target, session: event.cached, attempt }, effects)
|
||||
}
|
||||
|
||||
function cacheChanged<T, Scope>(
|
||||
state: Targeted<T, Scope>,
|
||||
session: T | undefined,
|
||||
): SessionResolutionTransition<T, Scope> {
|
||||
// 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 })
|
||||
}
|
||||
|
||||
if (state.status === "ready" && state.session === session) return unchanged(state)
|
||||
|
||||
return changed({ 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<T, Scope>(state: Targeted<T, Scope>, refresh: boolean): SessionResolutionTransition<T, Scope> {
|
||||
if (state.status === "ready") return changed(state, syncs(state.target, state.attempt, refresh))
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return changed({ status: "resolving", target: state.target, attempt }, syncs(state.target, attempt, true))
|
||||
}
|
||||
|
||||
function released<T, Scope>(state: SessionResolutionState<T, Scope>): SessionResolutionTransition<T, Scope> {
|
||||
if (state.status === "idle") return unchanged(state)
|
||||
|
||||
return changed({ status: "idle", attempt: state.attempt + 1 })
|
||||
}
|
||||
|
||||
// The timeline owns transcript errors, so only metadata reports back to the machine.
|
||||
function syncs<Scope>(
|
||||
target: SessionTarget<Scope>,
|
||||
attempt: number,
|
||||
metadata: boolean,
|
||||
): readonly SessionResolutionEffect<Scope>[] {
|
||||
if (!metadata) return [{ type: "sync.transcript", target }]
|
||||
|
||||
return [
|
||||
{ type: "sync.transcript", target },
|
||||
{ type: "sync.metadata", target, attempt },
|
||||
]
|
||||
}
|
||||
|
||||
function sameTarget<Scope>(left: SessionTarget<Scope>, right: SessionTarget<Scope>) {
|
||||
return left.scope === right.scope && left.sessionID === right.sessionID
|
||||
}
|
||||
|
||||
function changed<T, Scope>(
|
||||
state: SessionResolutionState<T, Scope>,
|
||||
effects: readonly SessionResolutionEffect<Scope>[] = [],
|
||||
): SessionResolutionTransition<T, Scope> {
|
||||
return { state, effects }
|
||||
}
|
||||
|
||||
function unchanged<T, Scope>(state: SessionResolutionState<T, Scope>): SessionResolutionTransition<T, Scope> {
|
||||
return { state, effects: [] }
|
||||
}
|
||||
@@ -5,21 +5,13 @@ import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useServer } from "@/runtime/server/current"
|
||||
import { ServerConnection, useServers } from "@/runtime/server/registry"
|
||||
import { useTabs } from "@/shell/tabs/tabs"
|
||||
import { isLocalSessionNotFoundError, isSessionNotFoundError } from "@/runtime/server/errors"
|
||||
import { isSessionNotFoundError } from "@/runtime/server/errors"
|
||||
import { ServerUnavailablePanel } from "./server-unavailable-panel"
|
||||
|
||||
export function SessionErrorFallback(props: { error: unknown; sessionID?: string; serverKey?: ServerConnection.Key }) {
|
||||
const language = useLanguage()
|
||||
const activeServer = useServer()
|
||||
const server = useServers()
|
||||
const tabs = useTabs()
|
||||
|
||||
const displayServer = createMemo(() => {
|
||||
const conn = server.list.find((item) => ServerConnection.key(item) === props.serverKey)
|
||||
|
||||
return conn ? server.label(conn) : props.serverKey
|
||||
})
|
||||
|
||||
const closeSession = () => {
|
||||
if (!props.sessionID) return
|
||||
tabs.removeSessionTab({ server: activeServer.key, sessionId: props.sessionID })
|
||||
@@ -31,45 +23,50 @@ export function SessionErrorFallback(props: { error: unknown; sessionID?: string
|
||||
fallback={<ServerUnavailablePanel reason="incompatible" onClose={props.sessionID ? closeSession : undefined} />}
|
||||
>
|
||||
<Show
|
||||
when={
|
||||
props.sessionID &&
|
||||
(isSessionNotFoundError(props.error, props.sessionID) ||
|
||||
isLocalSessionNotFoundError(props.error, props.sessionID))
|
||||
}
|
||||
when={props.sessionID && isSessionNotFoundError(props.error, props.sessionID) ? props.sessionID : undefined}
|
||||
fallback={<ErrorPage error={props.error} />}
|
||||
>
|
||||
<div class="flex-1 min-h-0 overflow-hidden">
|
||||
<div class="h-full px-6 pb-42 -mt-4 flex flex-col items-center justify-center text-center gap-4">
|
||||
<div class="flex flex-col items-center gap-2">
|
||||
<div class="text-16-medium text-text max-w-md">{language.t("session.error.notFound")}</div>
|
||||
<div class="text-13-regular text-text-weak max-w-md">
|
||||
{language.t("session.error.notFound.description")}
|
||||
</div>
|
||||
</div>
|
||||
<Show when={props.sessionID}>
|
||||
{(sessionID) => (
|
||||
<div class="max-w-full flex flex-col items-center gap-1">
|
||||
<div class="max-w-full text-11-regular text-text-faint break-all">{displayServer()}</div>
|
||||
<code class="max-w-full rounded-[4px] px-1 py-0.5 font-mono text-xs font-medium leading-4 text-text-base break-all bg-[color-mix(in_oklch,var(--v2-text-text-base)_8%,transparent)]">
|
||||
{sessionID()}
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
<Button
|
||||
variant="neutral"
|
||||
size="normal"
|
||||
icon="xmark-small"
|
||||
onClick={() => {
|
||||
if (!props.sessionID || !props.serverKey) return
|
||||
tabs.removeSessionTab({ server: props.serverKey, sessionId: props.sessionID })
|
||||
}}
|
||||
>
|
||||
{language.t("session.error.notFound.closeTab")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{(sessionID) => (
|
||||
<SessionNotFoundPanel sessionID={sessionID()} serverKey={props.serverKey ?? activeServer.key} />
|
||||
)}
|
||||
</Show>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
export function SessionNotFoundPanel(props: { sessionID: string; serverKey: ServerConnection.Key }) {
|
||||
const language = useLanguage()
|
||||
const server = useServers()
|
||||
const tabs = useTabs()
|
||||
|
||||
const displayServer = createMemo(() => {
|
||||
const conn = server.list.find((item) => ServerConnection.key(item) === props.serverKey)
|
||||
|
||||
return conn ? server.label(conn) : props.serverKey
|
||||
})
|
||||
|
||||
return (
|
||||
<div class="flex-1 min-h-0 overflow-hidden">
|
||||
<div class="h-full px-6 pb-42 -mt-4 flex flex-col items-center justify-center text-center gap-4">
|
||||
<div class="flex flex-col items-center gap-2">
|
||||
<div class="text-16-medium text-text max-w-md">{language.t("session.error.notFound")}</div>
|
||||
<div class="text-13-regular text-text-weak max-w-md">{language.t("session.error.notFound.description")}</div>
|
||||
</div>
|
||||
<div class="max-w-full flex flex-col items-center gap-1">
|
||||
<div class="max-w-full text-11-regular text-text-faint break-all">{displayServer()}</div>
|
||||
<code class="max-w-full rounded-[4px] px-1 py-0.5 font-mono text-xs font-medium leading-4 text-text-base break-all bg-[color-mix(in_oklch,var(--v2-text-text-base)_8%,transparent)]">
|
||||
{props.sessionID}
|
||||
</code>
|
||||
</div>
|
||||
<Button
|
||||
variant="neutral"
|
||||
size="normal"
|
||||
icon="xmark-small"
|
||||
onClick={() => tabs.removeSessionTab({ server: props.serverKey, sessionId: props.sessionID })}
|
||||
>
|
||||
{language.t("session.error.notFound.closeTab")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ErrorBoundary, createEffect, createMemo, Show, type ParentProps } from "solid-js"
|
||||
import { ErrorBoundary, createEffect, createMemo, Match, on, Show, Switch, type ParentProps } from "solid-js"
|
||||
import { Title } from "@solidjs/meta"
|
||||
import { useParams } from "@solidjs/router"
|
||||
import { createStore } from "solid-js/store"
|
||||
@@ -23,11 +23,13 @@ import { useSettings } from "@/settings/model"
|
||||
import { SessionUIProvider } from "@/shell/routes/session-ui-provider"
|
||||
import { useTabs, type PendingSession } from "@/shell/tabs/tabs"
|
||||
import { requireServerKey } from "@/shell/routes/session"
|
||||
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 { SessionErrorFallback } from "./route-error"
|
||||
import { SessionErrorFallback, SessionNotFoundPanel } from "./route-error"
|
||||
import { sessionRouteView } from "./resolution-machine"
|
||||
import { createSessionResolution } from "./session-resolution"
|
||||
import { SessionScreenView } from "./screen"
|
||||
import { PreparingComposer } from "./preparing-composer"
|
||||
@@ -106,14 +108,20 @@ function TargetSessionSettingsCommand() {
|
||||
return null
|
||||
}
|
||||
|
||||
// Session resolution never throws; this only catches render crashes. Every session tab on a server
|
||||
// shares the route, so a crash belongs to one target and clears when the tab changes.
|
||||
function SessionRouteErrorBoundary(props: ParentProps<{ sessionID?: string; serverKey?: ServerConnection.Key }>) {
|
||||
return (
|
||||
<ErrorBoundary
|
||||
fallback={(error) => (
|
||||
<SessionStatePanel>
|
||||
<SessionErrorFallback error={error} sessionID={props.sessionID} serverKey={props.serverKey} />
|
||||
</SessionStatePanel>
|
||||
)}
|
||||
fallback={(error, reset) => {
|
||||
createEffect(on([() => props.serverKey, () => props.sessionID], reset, { defer: true }))
|
||||
|
||||
return (
|
||||
<SessionStatePanel>
|
||||
<SessionErrorFallback error={error} sessionID={props.sessionID} serverKey={props.serverKey} />
|
||||
</SessionStatePanel>
|
||||
)
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</ErrorBoundary>
|
||||
@@ -126,56 +134,66 @@ function ResolvedTargetSessionRoute() {
|
||||
const tabs = useTabs()
|
||||
const data = useData()
|
||||
|
||||
const current = createSessionResolution(
|
||||
const resolution = createSessionResolution(
|
||||
() => params.id,
|
||||
() => data.session,
|
||||
{ children: true, connected: () => server.ctx.sdk.connection.status() === "connected" },
|
||||
)
|
||||
|
||||
const directory = createMemo(() => current()?.location.directory)
|
||||
const view = createMemo(() => sessionRouteView(resolution(), server.health))
|
||||
|
||||
// Only a failed health check: a version mismatch has its own panel, and a rejected credential is not an outage.
|
||||
const unreachable = () => {
|
||||
const health = server.health
|
||||
// Kept once the session leaves `ready`: the session providers can still read it while the route
|
||||
// swaps them out, where a narrowed <Match> value would throw a stale read.
|
||||
const directory = createMemo((previous: string) => {
|
||||
const current = view()
|
||||
|
||||
return !!health && !health.healthy && !health.checking && !health.unauthorized && !health.incompatible
|
||||
}
|
||||
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 (
|
||||
<Show
|
||||
when={!server.health?.incompatible}
|
||||
fallback={
|
||||
<Switch>
|
||||
<Match when={view().type === "incompatible"}>
|
||||
<SessionStatePanel>
|
||||
<ServerUnavailablePanel
|
||||
reason="incompatible"
|
||||
onClose={() => tabs.removeSessionTab({ server: server.key, sessionId: params.id })}
|
||||
/>
|
||||
<ServerUnavailablePanel reason="incompatible" onClose={closeTab} />
|
||||
</SessionStatePanel>
|
||||
}
|
||||
>
|
||||
<Show
|
||||
when={directory()}
|
||||
fallback={
|
||||
// Nothing is cached and an unreachable server never resolves the session, so explain instead of waiting blank.
|
||||
<Show when={unreachable()} fallback={<PendingSessionState sessionID={params.id} />}>
|
||||
<SessionStatePanel>
|
||||
<ServerUnavailablePanel
|
||||
reason="unreachable"
|
||||
onClose={() => tabs.removeSessionTab({ server: server.key, sessionId: params.id })}
|
||||
/>
|
||||
</SessionStatePanel>
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
</Match>
|
||||
{/* Not keyed: the session providers stay mounted while tabs switch between resolved sessions. */}
|
||||
<Match when={view().type === "ready"}>
|
||||
<LocationProvider directory={directory()}>
|
||||
<SessionUIProvider directory={directory()} server={server.key}>
|
||||
<TargetSessionPage />
|
||||
</SessionUIProvider>
|
||||
</LocationProvider>
|
||||
</Match>
|
||||
<Match when={view().type === "not-found"}>
|
||||
<SessionStatePanel>
|
||||
<SessionNotFoundPanel sessionID={params.id} serverKey={server.key} />
|
||||
</SessionStatePanel>
|
||||
</Match>
|
||||
<Match when={failure()} keyed>
|
||||
{(value) => (
|
||||
<LocationProvider directory={value()}>
|
||||
<SessionUIProvider directory={value()} server={server.key}>
|
||||
<TargetSessionPage />
|
||||
</SessionUIProvider>
|
||||
</LocationProvider>
|
||||
<SessionStatePanel>
|
||||
<ErrorPage error={value.error} />
|
||||
</SessionStatePanel>
|
||||
)}
|
||||
</Show>
|
||||
</Show>
|
||||
</Match>
|
||||
<Match when={view().type === "unreachable"}>
|
||||
<SessionStatePanel>
|
||||
<ServerUnavailablePanel reason="unreachable" onClose={closeTab} />
|
||||
</SessionStatePanel>
|
||||
</Match>
|
||||
<Match when={view().type === "resolving"}>
|
||||
<PendingSessionState sessionID={params.id} />
|
||||
</Match>
|
||||
</Switch>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,105 +1,92 @@
|
||||
import { createMemo, createRenderEffect, createSignal, on, onCleanup } from "solid-js"
|
||||
import { sessionNotFoundError } from "@/runtime/server/errors"
|
||||
import { createComputed, createMemo, createSignal, on, onCleanup, untrack } from "solid-js"
|
||||
import {
|
||||
createSessionResolutionState,
|
||||
transitionSessionResolution,
|
||||
type SessionResolutionEffect,
|
||||
type SessionResolutionEvent,
|
||||
} from "./resolution-machine"
|
||||
|
||||
type SessionStore<T> = {
|
||||
get: (id: string) => T | undefined
|
||||
sync: (id: string, options?: { children?: boolean }) => Promise<unknown>
|
||||
sync: (id: string, options?: { children?: boolean }) => Promise<void>
|
||||
message: {
|
||||
sync: (id: string) => Promise<unknown>
|
||||
sync: (id: string) => Promise<void>
|
||||
}
|
||||
pending: {
|
||||
sync: (id: string) => Promise<unknown>
|
||||
sync: (id: string) => Promise<void>
|
||||
}
|
||||
}
|
||||
|
||||
type Resolution<T> = { id: string; store: SessionStore<T> } & (
|
||||
| { state: "pending" }
|
||||
| { state: "settled" }
|
||||
| { state: "failed"; failure: unknown }
|
||||
)
|
||||
|
||||
// Reactive target session for the session route, read from the data store.
|
||||
// All session tabs on a server share one route instance, so the target session ID
|
||||
// changes in place; the effect is only a trigger that starts resolution for the
|
||||
// current target, and each run cancels the previous one through onCleanup so a
|
||||
// late result from an abandoned target is dropped. 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.
|
||||
//
|
||||
// The returned accessor is a pure derivation. The sync cache is authoritative, and
|
||||
// status only applies while it matches the current target (store + session ID): on
|
||||
// navigation or store replacement the memo re-evaluates before the trigger runs,
|
||||
// so trusting a previous target's settlement would fabricate a not-found for a
|
||||
// session that simply has not resolved yet. Resolve failures rethrow on read so
|
||||
// the enclosing SessionRouteErrorBoundary renders the scoped session error.
|
||||
// Drives the session route's resolution machine (resolution-machine.ts) from the data store.
|
||||
// All session tabs on a server share one route instance, so the target session ID changes in
|
||||
// place; each change is a new target for the machine, which rejects results from earlier ones.
|
||||
// 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<T>(
|
||||
sessionID: () => string | undefined,
|
||||
sessions: () => SessionStore<T>,
|
||||
options?: { children?: boolean; connected?: () => boolean },
|
||||
) {
|
||||
const cached = createMemo(() => {
|
||||
const id = sessionID()
|
||||
const [state, setState] = createSignal(createSessionResolutionState<T, SessionStore<T>>())
|
||||
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
|
||||
|
||||
if (!id) return
|
||||
const run = (effect: SessionResolutionEffect<SessionStore<T>>) => {
|
||||
const store = effect.target.scope
|
||||
const id = effect.target.sessionID
|
||||
|
||||
return sessions().get(id)
|
||||
})
|
||||
|
||||
const [status, setStatus] = createSignal<Resolution<T>>()
|
||||
|
||||
// Start independent reads before constructing the selected view, including
|
||||
// when its metadata is cached but its transcript has never been loaded.
|
||||
createRenderEffect(
|
||||
on([sessionID, sessions, () => options?.connected?.() ?? true] as const, ([id, store, connected]) => {
|
||||
if (!id || !connected) return
|
||||
let stale = false
|
||||
onCleanup(() => {
|
||||
stale = true
|
||||
})
|
||||
// The timeline owns message errors; metadata resolution stays independent. Queued inputs
|
||||
// ride along so a reconnect refreshes them with the transcript instead of leaving the
|
||||
// pre-disconnect queue on screen.
|
||||
if (effect.type === "sync.transcript") {
|
||||
void store.message.sync(id).catch(() => undefined)
|
||||
void store.pending.sync(id).catch(() => undefined)
|
||||
|
||||
if (cached() && !options?.children && !options?.connected) {
|
||||
setStatus({ id, store, state: "settled" })
|
||||
return
|
||||
}
|
||||
|
||||
store
|
||||
.sync(id, options?.children ? { children: true } : undefined)
|
||||
.then(() =>
|
||||
dispatch({ type: "sync.settled", target: effect.target, attempt: effect.attempt, session: store.get(id) }),
|
||||
)
|
||||
.catch((error) => dispatch({ type: "sync.failed", target: effect.target, attempt: effect.attempt, error }))
|
||||
}
|
||||
|
||||
const dispatch = (event: SessionResolutionEvent<T, SessionStore<T>>) => {
|
||||
const result = transitionSessionResolution(untrack(state), event)
|
||||
setState(() => result.state)
|
||||
result.effects.forEach(run)
|
||||
}
|
||||
|
||||
onCleanup(() => dispatch({ type: "disposed" }))
|
||||
|
||||
// Computations, not render effects, like the memo this machine replaced: a deleted session leaves
|
||||
// `ready` in the same pure phase that removed it, before the session subtree's render effects run.
|
||||
createComputed(
|
||||
on([sessionID, sessions] as const, ([id, store]) => {
|
||||
if (!id) {
|
||||
dispatch({ type: "target.changed", target: undefined, cached: undefined, connected: false, refresh })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
setStatus({ id, store, state: "pending" })
|
||||
store
|
||||
.sync(id, options)
|
||||
.then(() => {
|
||||
if (!stale) setStatus({ id, store, state: "settled" })
|
||||
})
|
||||
.catch((failure) => {
|
||||
if (!stale) setStatus({ id, store, state: "failed", failure })
|
||||
})
|
||||
const target = { scope: store, sessionID: id }
|
||||
const cached = createMemo(() => store.get(id))
|
||||
dispatch({ type: "target.changed", target, cached: cached(), connected: connected(), refresh })
|
||||
|
||||
// Owned by this target's run, so both are disposed before the next target is dispatched.
|
||||
createComputed(on(cached, (session) => dispatch({ type: "cache.changed", target, session }), { defer: true }))
|
||||
createComputed(
|
||||
on(
|
||||
connected,
|
||||
(value) => {
|
||||
if (value) dispatch({ type: "connected", target, refresh })
|
||||
},
|
||||
{ defer: true },
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
return createMemo(() => {
|
||||
const id = sessionID()
|
||||
|
||||
if (!id) return
|
||||
const value = cached()
|
||||
|
||||
if (value) return value
|
||||
const state = status()
|
||||
|
||||
if (!state || state.id !== id || state.store !== sessions()) return undefined
|
||||
|
||||
if (state.state === "failed") throw state.failure
|
||||
|
||||
// A session missing after settlement was deleted, possibly by another client.
|
||||
// Match the resolve error so the boundary shows the
|
||||
// session not found fallback.
|
||||
if (state.state === "settled") throw sessionNotFoundError(id)
|
||||
|
||||
return undefined
|
||||
})
|
||||
return state
|
||||
}
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { createRoot, createSignal } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import 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<Scope>(state: SessionResolutionState<Session, Scope>) {
|
||||
return state.status === "ready" ? state.session : undefined
|
||||
}
|
||||
|
||||
// Fake session store: get reads a reactive cache, sync returns a
|
||||
// deferred promise the test settles or fails explicitly. The session memo is
|
||||
// live (read below), so it recomputes eagerly on cache/status writes — throws
|
||||
// surface at the write site, which is also where the enclosing ErrorBoundary
|
||||
// would see them in the app. Assertions wrap write + read to cover both.
|
||||
// deferred promise the test settles or fails explicitly.
|
||||
function createFixture(initial: Record<string, Session> = {}) {
|
||||
const [cache, setCache] = createSignal(initial)
|
||||
const deferred = new Map<string, PromiseWithResolvers<unknown>>()
|
||||
const deferred = new Map<string, PromiseWithResolvers<void>>()
|
||||
const resolves: string[] = []
|
||||
const messages = { syncs: [] as string[], ...Promise.withResolvers<unknown>() }
|
||||
const pending = { syncs: [] as string[] }
|
||||
const messageSyncs: string[] = []
|
||||
const pendingSyncs: string[] = []
|
||||
const messages = { syncs: messageSyncs, ...Promise.withResolvers<void>() }
|
||||
const pending = { syncs: pendingSyncs }
|
||||
|
||||
return {
|
||||
resolves,
|
||||
@@ -27,7 +31,7 @@ function createFixture(initial: Record<string, Session> = {}) {
|
||||
get: (id: string) => cache()[id],
|
||||
sync: (id: string) => {
|
||||
resolves.push(id)
|
||||
const entry = deferred.get(id) ?? Promise.withResolvers<unknown>()
|
||||
const entry = deferred.get(id) ?? Promise.withResolvers<void>()
|
||||
deferred.set(id, entry)
|
||||
|
||||
return entry.promise
|
||||
@@ -49,10 +53,10 @@ function createFixture(initial: Record<string, Session> = {}) {
|
||||
},
|
||||
settle(id: string, directory = `/dir/${id}`) {
|
||||
setCache({ ...cache(), [id]: { id, directory } })
|
||||
deferred.get(id)?.resolve(undefined)
|
||||
deferred.get(id)?.resolve()
|
||||
deferred.delete(id)
|
||||
},
|
||||
fail(id: string, error: unknown) {
|
||||
fail(id: string, error: Error) {
|
||||
deferred.get(id)?.reject(error)
|
||||
// The real store does not cache failures: the inflight request entry is
|
||||
// dropped on rejection so the next resolve retries.
|
||||
@@ -84,7 +88,7 @@ test("refreshes the current session on reconnect while keeping cached content vi
|
||||
{ connected: () => connection.connected },
|
||||
)
|
||||
|
||||
expect(current()).toEqual(sessionOf("ses_a"))
|
||||
expect(resolved(current())).toEqual(sessionOf("ses_a"))
|
||||
expect(fixture.resolves).toEqual([])
|
||||
await flush()
|
||||
setConnection("connected", true)
|
||||
@@ -93,16 +97,16 @@ test("refreshes the current session on reconnect while keeping cached content vi
|
||||
await flush()
|
||||
|
||||
setConnection("connected", false)
|
||||
expect(current()).toEqual(sessionOf("ses_a"))
|
||||
expect(resolved(current())).toEqual(sessionOf("ses_a"))
|
||||
expect(fixture.resolves).toEqual(["ses_a"])
|
||||
setConnection("connected", true)
|
||||
expect(fixture.resolves).toEqual(["ses_a", "ses_a"])
|
||||
expect(current()).toEqual(sessionOf("ses_a"))
|
||||
expect(resolved(current())).toEqual(sessionOf("ses_a"))
|
||||
expect(fixture.messages.syncs).toEqual(["ses_a", "ses_a"])
|
||||
expect(fixture.pending.syncs).toEqual(["ses_a", "ses_a"])
|
||||
fixture.settle("ses_a", "/worktrees/moved")
|
||||
await flush()
|
||||
expect(current()?.directory).toBe("/worktrees/moved")
|
||||
expect(resolved(current())?.directory).toBe("/worktrees/moved")
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
@@ -113,7 +117,7 @@ test("starts metadata and messages in parallel once the route has a session ID",
|
||||
const [id, setId] = createSignal<string>()
|
||||
const current = createSessionResolution(id, () => fixture.sessions)
|
||||
|
||||
expect(current()).toBeUndefined()
|
||||
expect(current().status).toBe("idle")
|
||||
await flush()
|
||||
expect(fixture.resolves).toEqual([])
|
||||
expect(fixture.messages.syncs).toEqual([])
|
||||
@@ -122,13 +126,13 @@ test("starts metadata and messages in parallel once the route has a session ID",
|
||||
expect(fixture.resolves).toEqual(["ses_a"])
|
||||
expect(fixture.messages.syncs).toEqual(["ses_a"])
|
||||
|
||||
fixture.messages.resolve(undefined)
|
||||
fixture.messages.resolve()
|
||||
await flush()
|
||||
expect(current()).toBeUndefined()
|
||||
expect(current().status).toBe("resolving")
|
||||
|
||||
fixture.settle("ses_a")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_a")
|
||||
expect(resolved(current())?.id).toBe("ses_a")
|
||||
|
||||
dispose()
|
||||
})
|
||||
@@ -146,11 +150,11 @@ test("message failure does not fail metadata resolution", async () => {
|
||||
await flush()
|
||||
fixture.messages.reject(new Error("message sync failed"))
|
||||
await flush()
|
||||
expect(current()).toBeUndefined()
|
||||
expect(current().status).toBe("resolving")
|
||||
|
||||
fixture.settle("ses_a")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_a")
|
||||
expect(resolved(current())?.id).toBe("ses_a")
|
||||
|
||||
dispose()
|
||||
})
|
||||
@@ -166,20 +170,18 @@ test("re-resolves when navigating to an uncached session without a remount", asy
|
||||
const current = createSessionResolution(id, () => fixture.sessions)
|
||||
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_a")
|
||||
expect(resolved(current())?.id).toBe("ses_a")
|
||||
expect(fixture.resolves).toEqual([])
|
||||
expect(fixture.messages.syncs).toEqual(["ses_a"])
|
||||
|
||||
expect(() => {
|
||||
setId("ses_b")
|
||||
current()
|
||||
}).not.toThrow()
|
||||
setId("ses_b")
|
||||
expect(current().status).toBe("resolving")
|
||||
expect(fixture.resolves).toEqual(["ses_b"])
|
||||
expect(fixture.messages.syncs).toEqual(["ses_a", "ses_b"])
|
||||
|
||||
fixture.settle("ses_b")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_b")
|
||||
expect(resolved(current())?.id).toBe("ses_b")
|
||||
|
||||
dispose()
|
||||
})
|
||||
@@ -195,19 +197,19 @@ test("ignores a stale resolution failure after the target changes", async () =>
|
||||
|
||||
await flush()
|
||||
setId("ses_b")
|
||||
fixture.fail("ses_a", new Error("Session not found: ses_a"))
|
||||
fixture.fail("ses_a", new Error("resolve failed"))
|
||||
await flush()
|
||||
|
||||
expect(() => current()).not.toThrow()
|
||||
expect(current().status).toBe("resolving")
|
||||
fixture.settle("ses_b")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_b")
|
||||
expect(resolved(current())?.id).toBe("ses_b")
|
||||
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
|
||||
test("returning to a pruned session re-resolves instead of throwing not found", async () => {
|
||||
test("returning to a pruned session re-resolves instead of reporting not found", async () => {
|
||||
await createRoot(async (dispose) => {
|
||||
const fixture = createFixture()
|
||||
const [id, setId] = createSignal("ses_a")
|
||||
@@ -222,24 +224,21 @@ test("returning to a pruned session re-resolves instead of throwing not found",
|
||||
await flush()
|
||||
|
||||
fixture.remove("ses_a")
|
||||
expect(() => {
|
||||
setId("ses_a")
|
||||
current()
|
||||
}).not.toThrow()
|
||||
setId("ses_a")
|
||||
expect(current().status).toBe("resolving")
|
||||
expect(fixture.resolves).toEqual(["ses_a", "ses_b", "ses_a"])
|
||||
expect(fixture.messages.syncs).toEqual(["ses_a", "ses_b", "ses_a"])
|
||||
|
||||
fixture.settle("ses_a")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_a")
|
||||
expect(resolved(current())?.id).toBe("ses_a")
|
||||
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
|
||||
// A resolution that fails while its session is unfocused must not leave a
|
||||
// poisoned status behind: revisiting that session retries cleanly instead of
|
||||
// rethrowing the stale failure before the retry can start.
|
||||
// poisoned status behind: revisiting that session retries cleanly.
|
||||
test("revisiting a session whose resolution failed while unfocused retries cleanly", async () => {
|
||||
await createRoot(async (dispose) => {
|
||||
const fixture = createFixture()
|
||||
@@ -251,23 +250,21 @@ test("revisiting a session whose resolution failed while unfocused retries clean
|
||||
fixture.fail("ses_a", new Error("resolve failed"))
|
||||
await flush()
|
||||
|
||||
expect(() => {
|
||||
setId("ses_a")
|
||||
current()
|
||||
}).not.toThrow()
|
||||
setId("ses_a")
|
||||
expect(current().status).toBe("resolving")
|
||||
expect(fixture.resolves).toEqual(["ses_a", "ses_b", "ses_a"])
|
||||
expect(fixture.messages.syncs).toEqual(["ses_a", "ses_b", "ses_a"])
|
||||
|
||||
fixture.settle("ses_a")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_a")
|
||||
expect(resolved(current())?.id).toBe("ses_a")
|
||||
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
|
||||
// The session accessor is reactive: replacing the data store (for example after
|
||||
// the server context is rebuilt) must gate out the old store's status and
|
||||
// the server context is rebuilt) must gate out the old store's results and
|
||||
// re-resolve against the new one instead of fabricating a not-found.
|
||||
test("re-resolves against a replaced session store", async () => {
|
||||
await createRoot(async (dispose) => {
|
||||
@@ -279,12 +276,10 @@ test("re-resolves against a replaced session store", async () => {
|
||||
await flush()
|
||||
first.settle("ses_a")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_a")
|
||||
expect(resolved(current())?.id).toBe("ses_a")
|
||||
|
||||
expect(() => {
|
||||
setStore(second.sessions)
|
||||
current()
|
||||
}).not.toThrow()
|
||||
setStore(second.sessions)
|
||||
expect(current().status).toBe("resolving")
|
||||
await flush()
|
||||
expect(second.resolves).toEqual(["ses_a"])
|
||||
expect(first.messages.syncs).toEqual(["ses_a"])
|
||||
@@ -292,32 +287,33 @@ test("re-resolves against a replaced session store", async () => {
|
||||
|
||||
second.settle("ses_a")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_a")
|
||||
expect(resolved(current())?.id).toBe("ses_a")
|
||||
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
|
||||
// The viewed session is pinned in the cache, so disappearing after settlement
|
||||
// means it was deleted; the boundary must show the not found fallback.
|
||||
test("throws not found when the settled session is deleted", async () => {
|
||||
// The viewed session is pinned in the cache, so disappearing after it resolved
|
||||
// means it was deleted. The next tab on the same route still resolves.
|
||||
test("reports a deleted session as not found until the route targets another session", async () => {
|
||||
await createRoot(async (dispose) => {
|
||||
const fixture = createFixture()
|
||||
|
||||
const current = createSessionResolution(
|
||||
() => "ses_a",
|
||||
() => fixture.sessions,
|
||||
)
|
||||
const [id, setId] = createSignal("ses_a")
|
||||
const current = createSessionResolution(id, () => fixture.sessions)
|
||||
|
||||
await flush()
|
||||
fixture.settle("ses_a")
|
||||
await flush()
|
||||
expect(current()?.id).toBe("ses_a")
|
||||
expect(resolved(current())?.id).toBe("ses_a")
|
||||
|
||||
expect(() => {
|
||||
fixture.remove("ses_a")
|
||||
current()
|
||||
}).toThrow("Session not found: ses_a")
|
||||
fixture.remove("ses_a")
|
||||
expect(current().status).toBe("not-found")
|
||||
|
||||
setId("ses_b")
|
||||
expect(current().status).toBe("resolving")
|
||||
fixture.settle("ses_b")
|
||||
await flush()
|
||||
expect(resolved(current())?.id).toBe("ses_b")
|
||||
|
||||
dispose()
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user